PHP Programmimg
PHP Programmimg
INTRODUCTION
2
DYNAMIC WEB PAGE
3
PHP COMPARE
4
ASP.NET
This is the latest incarnation of ASP, though in fact it ’ s been rebuilt from the ground
up. It ’ s actually a framework of libraries that you can use to build Web sites, and you
have a
choice of languages to use, including C#, VB.NET (Visual Basic), and J# (Java).
Because ASP.NET
gives you a large library of code for doing things like creating HTML forms and
accessing
database tables, you can get a Web application up and running very quickly. PHP,
although it
has a very rich standard library of functions, doesn ’ t give you a structured framework
to the
extent that ASP.NET does. On the other hand, plenty of free application frameworks
and
libraries are available for PHP, such PEAR (discussed later in this book) and the Zend
Framework. Many would argue that C# is a nicer, better - organized language to
program in than
PHP, although C# is arguably harder to learn. Another advantage of ASP.NET is that C#
is a
compiled language, which generally means it runs faster than PHP ’ s interpreted
scripts
5
(although PHP compilers are available).
ASP (ACTIVE SERVER PAGES)
This venerable Microsoft technology has been around since 1997, and
was one of the first Web application technologies to integrate closely
with the Web server,resulting in fast performance. ASP scripts are
usually written in VBScript, a language derived from BASIC. This
contrasts with PHP ’ s more C - like syntax. Although both languages
have their fans, I personally find that it ’ s easier to write structured,
modular code in PHP than in VBScript.
6
PERL
Perl was one of the first languages used for creating dynamic Web pages,
initially through
the use of CGI scripting and, later, integrating tightly into Web servers with
technologies like the
Apache mod_perl module and ActivePerl for IIS. Though Perl is a powerful
scripting language,
it ’ s harder to learn than PHP. It ’ s also more of a general - purpose
language than PHP, although
Perl ’ s CPAN library includes some excellent modules for Web
development.
7
JAVA
Like Perl, Java is another general - purpose language that is commonly used for Web
application development. Thanks to technologies like JSP (JavaServer Pages) and
servlets, Java
is a great platform for building large - scale, robust Web applications. With software
such as
Apache Tomcat, you can easily build and deploy Java - based Web sites on virtually
any server
platform, including Windows, Linux, and FreeBSD. The main downside of Java
compared to
PHP is that it has quite a steep learning curve, and you have to write a fair bit of code
to get
even a simple Web site going (though JSP helps a lot in this regard). In contrast, PHP
is a simpler
language to learn, and it ’ s quicker to get a basic Web site up and running with PHP.
Another
drawback of Java is that it ’ s harder to find a Web hosting company that will support
JSP,
whereas nearly all hosting companies offer PHP hosting.
8
PYTHON
9
RUBY RUBY
Like Python, Ruby is another general - purpose language that has gained a
lot of traction
with Web developers in recent years. This is largely due to the excellent
Ruby on Rails
application framework, which uses the Model - View - Controller (MVC)
pattern, along with
Ruby ’ s extensive object - oriented programming features, to make it easy
to build a complete
Web application very quickly. As with Python, Ruby is fast becoming a
popular choice among Web
developers, but for now, PHP is much more popular.
10
COLD FUSION
Along with ASP, Adobe ColdFusion was one of the first Web application
frameworks available, initially released back in 1995. ColdFusion ’ s main
selling points are that it ’ s easy to learn, it lets you build Web applications
very quickly, and it ’ s really easy to create
database - driven sites.
An additional plus point is its tight integration with Flex, another Adobe
technology that allows you to build complex Flash - based Web
applications. ColdFusion ’ s main disadvantages compared to PHP include
the fact that it ’ s not as popular (so it ’ s harder to find
hosting and developers), it ’ s not as flexible as PHP for certain tasks, and
the server software to run your apps can be expensive. (PHP and Apache
are, of course, free and open source.)
11
THE EVOLUTION OF PHP
Although PHP only started gaining popularity with Web developers around 1998, it was created by
Rasmus Lerdorf way back in 1994. PHP started out as a set of simple tools coded in the C language
to
replace the Perl scripts that Rasmus was using on his personal home page (hence the original
meaning of the “ PHP ” acronym). He released PHP to the general public in 1995, and called it PHP
version 2.
In 1997, two more developers, Zeev Suraski and Andi Gutmans, rewrote most of PHP and, along with
Rasmus, released PHP version 3.0 in June 1998. By the end of that year, PHP had already amassed
tens of thousands of developers, and was being used on hundreds of thousands of Web sites.
For the next version of PHP, Zeev and Andi set about rewriting the PHP core yet again, calling it the
“ Zend Engine ” (basing the name “ Zend ” on their two names). The new version, PHP 4, was
launched inMay 2000. This version further improved on PHP 3, and included session handling
features, output
buffering, a richer core language, and support for a wider variety of Web server platforms.
Although PHP 4 was a marked improvement over version 3, it still suffered from a relatively poor
object - oriented programming (OOP) implementation. PHP 5, released in July 2004, addressed this
issue, with
private and protected class members; final, private, protected, and static methods; abstract classes;
interfaces; and a standardized constructor/destructor syntax.
12
PHP TOOLS
FuelPHP
CakePHP
FlightPHP
Symfony
yiiFramework
Laravel
Zend
Codeigniter
Phalcon PHP
Agavi
13
FUELPHP
14
CAKEPHP
15
FLIGHTPHP
16
SYMFONY
17
YIIFRAMEWORK
18
LARAVEL
19
ZEND
20
CODEIGNITER
21
PHALCON PHP
22
PHPIXIE
23
AGAVI
24
TESTING PHP SERVER
< ?php
phpinfo();
?>
25
HELLO.PHP
<?php
Hello World
?>
26
COMMENT
PHP supports single - line comments and multi - line comments. To write a
single - line comment, start the
line with either two slashes (//) or a hash symbol (#). For example:
// This code displays the current time
27
INTEGER
<?php
print "Hello World!"."<br>";
$com= 90;
print $com;
print "<br>";
print gettype($com);
return(true);
?>
28
SCALAR DATA TYPE DESCRIPTION EXAMPLE
29
FUNCTION DESCRIPTION
30
DATE AND TIME
<?php
print date("d D M Y")."<br>";
print date("g:1:s a");
return(true);
?>
32
TYPE DESCRIPTION
33
CIRCUMFERENCE
<?php
print "<b>"."Area of circle"."</b>"."<br>";
$rd=4.0;
$area=M_PI * pow($rd,2);
print "Area of circle with radius ".$rd." is ".$area;
return(true);
?>
34
FOR LOOP
<?php
print "<b>"."Area of circle"."</b>"."<br>";
$rd=0;
for($rd=0;$rd<=4;$rd++)
{
$area=M_PI * pow($rd,2);
print "Area of circle with radius ".$rd." is ".$area."<br>";
}
return(true);
?>
35
WHILE LOOP
<?php
print "<b>"."Circumference of circle"."</b>"."<br>";
$rd=0;
while($rd<=4)
{
$cir=2 * M_PI * $rd;
print "Circumference of circle with radius ".$rd." is ".$cir."<br>";
$rd++;
}
return(true);
?>
36
DO WHILE
<?php
print "<b>"."Circumference of circle"."</b>"."<br>";
$rd=0;
do
{
$cir=2 * M_PI * $rd;
print "Circumference of circle with radius ".$rd." is ".$cir."<br>";
$rd++;
}while($rd<=4);
return(true);
?>
37
ESCAPE CHARACTERS
38
FUNCTION CASE - INSENSITIVE EQUIVALENT
strstr() stristr()
strpos() stripos()
strrpos() strripos()
str_replace() str_ireplace()
39
STRING
<?php
$str="Welcome";
print " <h1>to PHP world,$str </h1> <br>";
$myArray["age"]=34;
print "My age is".$myArray["age"];
?>
40
STRING FORMAT
<?php
$num=456.98;
print "Binary: %b <br>".$num;
print "Character: %c <br> ".$num;
print "Decimal: %d <br>".$num;
print "Scientific: %e <br>".$num;
print "Float: %f <br>".$num;
print "Octal: %o <br>".$num;
print "String: %s <br>".$num;
print "Hex(lowercase): %x <br>".$num;
print "Hex(uppercase): %X <br>".$num;
return(true);
?>
41
TRIM FUNCTIONS
trim() removes white space from the beginning and end of a string
ltrim() removes white space only from the beginning of a string
rtrim() removes white space only from the end of a string
42
EXAMPLE
<?php
$myString = " What a lot of space! ";
echo " < pre > ";
echo "|" . trim( $myString ) . "|\n"; // Displays "|What a lot of
space!|";
echo "|" . ltrim( $myString ) . "|\n"; // Displays "|What a lot of
space! |";
echo "|" . rtrim( $myString ) . "|\n"; // Displays "| What a lot of
space!|";
echo " < /pre > ";
?>
43
STRING FUNCTIONS
strstr() tells you whether the search text is within the string
strpos() and strrpos() return the index position of the first and last
occurrence of the search text, respectively
substr_count() tells you how many times the search text occurs within the
string
strpbrk() searches a string for any of a list of characters
44
PRINTING RANGE OF ARRAY
<?php
$authors = array("Steinbeck", "Kafka", "Tolkien", "Dickens");
$myBook = array("title" => "The Grapes of Wrath",
"author" => "John Steinbeck", "pubYear" => 1939);
echo ' <h2> $authors: </h2> <pre> ';
print_r ($authors);
echo ' </pre > <h2> $myBook: </h2 > <pre> ';
print_r ($myBook);
echo " </pre> ";
?>
45
FOR EACH
<?php
$myBook = array( "<b>Title</b>" => "The Grapes of Wrath",
"<b>Author</b>" => "John Steinbeck",
"<b>PubYear</b>" => 1939 );
echo "<h1> Usin Each() While loop </h1>";
while ($element = each( $myBook ) ) {
echo "<dd> $element[0]</dd>";
echo "<dd> $element[1]</dd>";
}
?>
46
FOREACH
<?php
echo "<h1> Using Foreach() While loop </h1>";
$authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens"
);
foreach ( $authors as $val ) {
echo $val . "<br>";
}
?>
47
VARIABLE AS FUNCTION
<?php
$squareRoot = "sqrt";
echo "The square root of
9 is: " . $squareRoot( 9
)."<br>";
echo "All done! <br>";
?>
48
FUNCTION
<?php
$trigFunctions = array( "sin", "cos", "tan" );
$degrees = 30;
foreach ( $trigFunctions as $trigFunction ) {
echo "$trigFunction($degrees) = " . $trigFunction( deg2rad(
$degrees ) )
. " <br> ";
}
?>
49
FUNCTION
<?php
function makeBold( $text ) {
return "<b> $text </b>";
}
$normalText = "This is normal text.";
$boldText = makeBold( "This is bold text." );
echo " <p> $normalText </p> ";
echo " <p> $boldText </p> ";
?>
50
CLASS
<?php
class Car {
public $color;
public $manufacturer;
}
$beetle = new Car();
$beetle-> color = "red";
$beetle-> manufacturer = "Volkswagen";
$mustang = new Car();
$mustang-> color = "green";
$mustang-> manufacturer = "Ford";
echo " <h2> Some properties: </h2> ";
echo " <p> The Beetle’s color is " . $beetle-> color . ". </p> ";
echo " <p> The Mustang’s manufacturer is " . $mustang-> manufacturer . ". </p> ";
echo " <h2> The \$beetle Object: </h2> <pre> ";
print_r( $beetle );
echo " < /pre > ";
echo " <h2> The \$mustang Object: </h2> <pre> ";
print_r( $mustang );
echo " </pre> ";
?>
51
MYCLASS
<?php
class MyClass {
public function getGreeting() {
return "Hello, World!";
}
public function hello() {
echo $this->getGreeting();
}
}
$obj = new MyClass;
$obj-> hello(); // Displays "Hello, World!";
?>
52
PROPERTIES
53
CLASS CAR
<?php
class Car {
public function __get( $propertyName ) {
echo "The value of '$propertyName' was requested <br> ";
return "blue";
}
}
$car = new Car;
$x = $car-> color; // Displays “The value of ‘color’ was requested”
echo "The car's color is $x <br> "; // Displays “The car’s color is blue”
?>
54
FILES READ AND WRITE
<?php
$counterFile = "./count.dat";
if ( !file_exists( $counterFile ) ) {
if ( !( $handle = fopen( $counterFile, "w" ) ) ) {
die( "Cannot create the counter file." );
} else {
fwrite( $handle, 0 );
fclose( $handle );
}
}
if ( !( $handle = fopen( $counterFile, "r" ) ) ) {
die( "Cannot read the counter file." );
}
$counter = (int) fread( $handle, 20 );
fclose( $handle );
$counter++;
echo "<p>You’re visitor No. $counter.</p>";
if ( !( $handle = fopen( $counterFile, "w") ) ){
die( "Cannot open the counter file for writing." );}
else{
fwrite( $handle, $counter++ );
}
fclose( $handle );
?>
56
METHODS IN FORM (HTML)
$_GET Contains a list of all the field names and values sent by a form using
the get method
$_POST Contains a list of all the field names and values sent by a form
using
the post method
$_REQUEST Contains the values of both the $_GET and $_POST arrays
combined
57
HTML FORM
Testphp.php
<html>
<head>
<title>hello user</title>
</head>
<body>
<H1> Welcome</h1>
<form action="test1.php" method="post">
Name: <input type="text" name="username" />
<input type="submit" value="submit"/>
</form>
</body>
</html>
Test1.php
<?php
$content=$_REQUEST['username'];
echo "Hello !" . $content . ".<br />";
echo "You have visited the Server Page"
?>
58
DATABASE CONNECTIVITY
59
PHP & MYSQL CONNECTIVITY
Selectphp.php
<html>
<head> <title>Welcome </title></head><body>
<h1>Hello It is time Renew! </h1>
if($name)
{ 61
$query = "SELECT customer_name,customer_id ,customer_email,customer_mbno FROM customers WHERE customer_name = '" . $name . "';";
DATABASE CONNECTIVITY
Selectphp.php
<html>
<head> <title>Welcome </title></head><body>
<h1>Hello It is time Renew! </h1>
if($name)
{ 62
$query = "SELECT customer_name,customer_id ,customer_email,customer_mbno FROM customers WHERE customer_name = '" . $name . "';";
INSERT
<form action
1. Call Insertphp.php
63
UPDATE
Call updatephp.php
64
DELETE
Call deletephph.php
65
STORED PROCEDURE
<?php
$mysqli = new mysqli("localhost", "root", "", "mydbase");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id
INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
!$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id)
VALUES(id_val); END;")) {
echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$mysqli->query("CALL p(1)")) {
echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!($res = $mysqli->query("SELECT id FROM test"))) {
echo "SELECT failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
var_dump($res->fetch_assoc()); 66
STORED PROCEDURE
<?php
$mysqli = new mysqli("localhost", "root", "", "mydbase");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli-
>connect_error;
}
if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
!$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!"
INTO msg; END;')) {
echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$mysqli->query("SET @msg = ''") || !$mysqli->query("CALL p(@msg)")) {
echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!($res = $mysqli->query("SELECT @msg as _p_out"))) {
echo "Fetch failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$row = $res->fetch_assoc();
echo $row['_p_out'];
?> 67
RESULT SET
<?php
$mysqli = new mysqli("localhost", "root", "", "mydbase");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
!$mysqli->query("CREATE TABLE test(id INT)") ||
!$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
!$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;')){
echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$mysqli->multi_query("CALL p()")) {
echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
printf("---<br>");
var_dump($res->fetch_all());
printf("---<br>");
$res->free();
} else {
if ($mysqli->errno) {
echo "Store failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
}
} while ($mysqli->more_results() && $mysqli->next_result()); 68
?>
IMAGES
Creating Images
Now that you understand the some basic image concepts, you can start writing scripts
to generate
images. Creating an image in PHP requires four steps:
1. Create a blank image canvas for PHP to work with. This is an area of the Web
server ’ s memory
that is set aside for drawing onto.
2. Work through the steps involved in drawing the image that you want. This includes
setting up
colors and drawing the shapes and text that you want within your image.
3. Send your finished image to the Web browser or save it to disk.
4. Remove your image from the server ’ s memory.
69
IMAGES
70
DRAW LINE
<?php
$myImage = imagecreate( 200, 100 );
$myGray = imagecolorallocate( $myImage, 204, 204, 204 );
$myBlack = imagecolorallocate( $myImage, 0, 0, 0 );
imageline( $myImage, 15, 35, 120, 60, $myBlack );
header( "Content-type: image/png" );
imagepng( $myImage );
imagedestroy( $myImage );
?>
71
DRAW RECTANGLE
<?php
$myImage = imagecreate( 200, 100 );
$myGray = imagecolorallocate( $myImage, 204, 204, 204 );
$myBlack = imagecolorallocate( $myImage, 0, 0, 0 );
imagerectangle( $myImage, 15, 35, 120, 60, $myBlack );
header( "Content-type: image/png" );
imagepng( $myImage );
imagedestroy( $myImage );
?>
72
DRAW ELLIPSE & CIRCLE
<?php
$myImage = imagecreate( 200, 100 );
$myImage1 = imagecreate( 300, 200 );
$myGray = imagecolorallocate( $myImage, 204, 204, 204 );
$myBlack = imagecolorallocate( $myImage,120, 0, 0 );
imageellipse( $myImage, 90, 60, 160, 50, $myBlack );
imageellipse( $myImage, 90, 60, 70, 70, $myBlack );
header( "Content-type: image/png" );
imagepng( $myImage );
imagedestroy( $myImage );
?>
73
LOAD IMAGE
<?php
$myImage = imagecreatefromjpeg( "greenapple.jpg" );
header( "Content-type: image/jpeg" );
imagejpeg( $myImage );
imagedestroy( $myImage );
?>
74
WATERMARKING
<?php
$myImage = imagecreatefromjpeg( "image005.jpg" );
$myCopyright = imagecreatefrompng( "GACL2.png" );
$destWidth = imagesx( $myImage );
$destHeight = imagesy( $myImage );
$srcWidth = imagesx( $myCopyright );
$srcHeight = imagesy( $myCopyright );
$destX = ($destWidth - $srcWidth) / 2;
$destY = ($destHeight - $srcHeight) / 2;
imagecopy( $myImage, $myCopyright, $destX, $destY, 0, 0, $srcWidth,
$srcHeight );
header( "Content-type: image/jpeg" );
imagejpeg( $myImage );
imagedestroy( $myImage );
imagedestroy( $myCopyright );
?>
75
MONGO DB CONNECTION
76
MONGO DB CONNECTION
<?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully"."<br>";
// select a database
$db = $m->mydb;
echo "Database mydb selected";
?>
77
MONGO DB COLLECTION
<?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// select a database
$db = $m->mydb;
echo "Database mydb selected";
$collection = $db->Dime;
echo "Collection selected successfully";
$cursor = $collection->find();
// iterate cursor to display title of documents
foreach ($cursor as $document) {
echo $document["name"] . "\n";
}
?>
78
REGULAR EXPRESSION
PHP ’ s main pattern - matching function is preg_match() . This function takes the
following arguments:
The regular expression to search for (as a string)
The string to search through
An optional array to store any matched text in. (The matched text is stored in
the first element.)
An optional integer specifying any flags for the match operation. Currently
only one flag issupported: PREG_OFFSET_CAPTURE . Pass this constant to
get preg_match() to return the position of any match in the array as well as
the text matched. (If you need to pass a fifth argument to preg_match() and
you want to turn off this feature, specify a value of zero instead.)
An optional integer offset from the start of the string (the first character has an
offset of zero, the second character has an offset of 1, and so on). If
specified, preg_match() starts the search from this position in the string,
rather than from the first character.
80
PATTERN MATCHING
Pattern_replace2.php
<?php
$text = array(
"Mouse mat: $3.99",
"Keyboard cover: $4.99",
"Screen protector: $5.99"
);
$newText = preg_replace( "/\\$\d+\.\d{2}/", "Only $0", $text );
echo "<pre>";
print_r( $newText );
echo "</pre> ";
?>
81
PATTERN MATCHING
Pattern_replace1.php
<?php
$text = "The wholesale price is $89.50. " .
"The product will be released on Jan 16, 2010.";
$patterns = array(
"/\\$\d+\.\d{2}/",
"/\w{3} \d{1,2}, \d{4}/"
);
$replacements = array(
"[PRICE CENSORED]"
);
echo preg_replace( $patterns, $replacements, $text );
?>
82
PATTERN MATCHING
Pattern_replace.php
<?php
$text = "Our high-quality mouse mat is just $3.99,
while our keyboard covers sell for $4.99 and our
screen protectors for only $5.99.";
function addADollar( $matches ) {
return "$" . ( $matches[1] + 1 );
}
echo preg_replace_callback( "/\\$(\d+\.\d{2})/", "addADollar", $text );
?>
83
SPLIT IN PATTERN MATCHING
<?php
$text = "John Steinbeck, Franz Kafka and J.R.R. Tolkien";
$authors = preg_split( "/,\s*|\s+and\s+/", $text );
echo "<pre>";
print_r( $authors )."</br>";
echo " </pre> ";
?>
84
PATTERN MATCHING
85
PREG_MATCH IN PATTERN MATCHING
<?php
$text = "Hello, world!\nHow are you today?\n";
echo preg_match( "/world!$/", $text ) . "<br/>"; // Displays "0"
echo preg_match( "/world!$/m", $text ) . "<br/>"; // Displays "1"
$text = "Andy scored 184 points, Rachel attained 198 points and Bert scored
112 points.";
$pattern = "/
(Andy|Rachel|Bert)\ # Only match people we know about
(scored|attained)\ # Two words, same meaning
(\d+) # The number of points scored
/x";
preg_match_all( $pattern, $text, $matches );
for ( $i = 0; $i < count( $matches[0] ); $i++ ) {
echo $matches[1][$i] . ": " . $matches[3][$i] . "<br/>";
}
?>
86
PATTER MATCHING EXAMPLE
<?php
if ( isset( $_POST["submitted"] ) ) {
processForm();
} else {
displayForm();
function displayForm() {
?>
<h2>Please enter your order details below then click Send Order:</h2>
<div>
<label> </label>
</div>
</form>
digits.)</p>
<?php
function processForm() {
$errorMessages = array();
$emailAddressPattern = "/
^ # Start of string
#. 87
\@
XML — eXtensible Markup Language — lets you create text documents that can
hold data in a
structured way. It was originally designed to be a human - readable means of
exchanging structured
data, but it has also gained ground very quickly as a means of storing structured
data.
88
XML
89
READING XML DOCUMENT WITH PHP
<stockList>
<h1>Fruits and Vegetables</h1>
<item type="fruit">
<b><name> Apple </name> </b>
<unitPrice> 0.99, </unitPrice>
<quantity> 412 </quantity>
</item><br>
<item type="vegetable">
<b><name> Beetroot </name></b>
<unitPrice> 1.39, </unitPrice>
<quantity> 67 </quantity>
</item>
</stockList>
90
READING XML DOCUMENT WITH PHP
Web Services, including languages such as SOAP for exchanging information in XML
format over HTTP, XML - RPC (SOAP ’ s simpler ancestor), and the Web Services
Description Language (WSDL), used for describing Web ServicesNon - empty elements can be created from start and
end tags (like the < p > ... < /p > tags in
XHTML). Empty elements should be created using the special empty - element tag format (like
the < br/ > tag in XHTML). Unlike HTML, you cannot have a start tag that isn ’ t followed
by an end tag.
Application file formats, such as OpenOffice ’ s OpenDocument Format (ODF) and
Microsoft ’ s Office Open XML (OOXML) that are used to store word processing
documents, spreadsheets, and so on.
RSS and Atom news feeds that allow Web applications to publish news stories in a
universal format that can be read by many types of software, from news readers and email
clients through to other Web site applications.
91
READING XML DOCUMENT WITH PHP
XML elements are declared to be either non - empty, in which case they are designed to contain
data; or empty, in which case they cannot contain data. For example, in XHTML, the p
(paragraph) element is non - empty because it can contain text, whereas the br (line - break)
element is empty because it cannot contain anything.
Non - empty elements can be created from start and end tags (like the < p > ... < /p > tags in
XHTML). Empty elements should be created using the special empty - element tag format (like
the < br/ > tag in XHTML). Unlike HTML, you cannot have a start tag that isn ’ t followed
by an end tag.
XML attributes are written inside the start tags of non - empty elements, or inside the empty -
element tags of empty elements, and must be of the format name= “ value ” or name=’value’ .
No attribute name may appear more than once inside any given element. For example:
< item type=”vegetable” > ... < /item >
< emptyElement color=’red’ / >
XML elements must be properly nested, meaning any given element ’ s start and end tags must
be outside the start and end tags of elements inside it, and inside the start and end tags of its
enclosing element.
92
READING XML DOCUMENT WITH PHP
93
CREATING XML PARSER TO READ XML
DOCUMENT
The process of using XML Parser to read an XML document usually breaks down
like this:
1. Create a new parser resource by calling the xml_parser_create() function.
2. Create two event handler functions to handle the start and end of an XML
element, then register
these functions with the parser using the xml_set_element_handler() function.
3. Create another event handler function to handle any character (text) data that
may be found
inside an element, and register this function with the parser using
xml_set_character_data_handler() .
4. Parse the XML document by calling the xml_parse() function, passing in the
parser and the
XML string to parse.
5. Finally, destroy the parser resource, if it ’ s no longer needed, by calling
xml_parser_free() .
94
XML DOCUMENT
95
XML DOCUMENT
96
XML DOCUMENT
97
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://127.0.0.1/TR/xhtml1/DTD/xhtml1-strict.dtd">
XML DOCUMENT
<html xmlns="http://127.0.0.1/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>
<pre>
<?php
/*
*/
echo "\n";
/*
<?php
if ( isset( $_POST["sendPhoto"] ) ) {
processForm();
} else {
displayForm();
function processForm() {
UPLOAD_ERR_OK ) {
if ( $_FILES["photo"]["type"] != "image/jpeg" ) {
$_FILES["photo"]["error"] ;
} else {
displayThanks();
} else {
switch( $_FILES["photo"]["error"] ) {
case UPLOAD_ERR_INI_SIZE:
break;
case UPLOAD_ERR_FORM_SIZE:
break;
case UPLOAD_ERR_NO_FILE:
99
$message = "No file was uploaded. Make sure you choose a file to
UPLOAD PHOTO
function displayForm() {
?>
<h1>Uploading a Photo</h1>
<p>Please enter your name and choose a photo to upload, then click
Send Photo.</p>
<form action="photo_upload.php" method="post" enctype="multipart/
form-data">
<div style="width: 30em;">
<input type="hidden" name="MAX_FILE_SIZE" value="50000">
<label for="visitorName">Your name</label>
<input type="text" name="visitorName" id="visitorName" value="">
<label for="photo">Your photo</label>
<input type="file" name="photo" id="photo" value="">
<div style="clear: both;">
<input type="submit" name="sendPhoto" value="Send Photo">
</div>
</div>
</form>
<?php
}
function displayThanks() {
?>
<h1>Thank You</h1>
<p>Thanks for uploading your photo<?php if ( $_POST["visitorName"] )
echo ", ".$_POST["visitorName"] ?>!</p>
<p>Here’s your photo:</p>
<p><img src="photos/<?php echo $_FILES["photo"]["name"]?>” alt="Photo" 100
/></p>
THANK YOU
101