2. INTRODUCTION
PHP is a programming language for building dynamic, interactive Web
sites.
PHP programs run on a Web server, and serve Web pages to visitors on
request.
PHP is that you can embed PHP code within HTML Web pages, making it
very easy for you to create dynamic content quickly.
2
3. DYNAMIC WEB PAGE
A dynamic Web page is a page whose contents can change automatically
each time the page is viewed.
It ’ s displayed (at leastuntil the page is next edited). Meanwhile, an
interactive Web site is a site that responds to input from its visitors.
A Web forum is a good example — users can post new messages to the
forum, which are then displayed on the site for all to see.
3
4. PHP COMPARE
PHP compare with other common Web programming technologies-
ASP (Active Server Pages)
ASP.NET
Perl
Java
Python
Ruby
Cold Fusion
4
5. 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
(although PHP compilers are available).
5
6. 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
7. 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
8. 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
9. PYTHON
Conceived in the late 1980s, Python is another general - purpose
programming language that is now commonly used to build dynamic Web
sites. Although it doesn ’ t have much in the way of Web - specific features
built into the language, many useful modules and frameworks,
such as Zope and Django, are available that make building Web
applications relatively painless.
Many popular sites such as Google and YouTube are built using Python,
and Python Web hosting is starting to become much more common
(though it ’ s nowhere near as common as
PHP hosting).
You can even build and host your Python apps on Google ’ s server with
the
Google App Engine. Overall, Python is a very nice language, but PHP is
currently a lot more popular, and has a lot more built - in functionality to
help with building Web sites.
9
10. 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.
RUBY
10
11. 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
12. 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
14. FUELPHP
Fuel PHP works based on Model View Control
and having Innovative plug ins.
FuelPHP supports router based theory
where you might route directly to a nearer the input uri,
making the closure the controller and
giving it control of further execution.
14
15. CAKEPHP
Cake PHP is a great source to build up simple and
great web application in an easy way.
Some great feature which are inbuilt in php are input validation,
SQL injection prevention that keeps you application safe and secure.
Features
Build Quickly
No need to configure
MIT licence
MVC Model
Secure
15
16. FLIGHTPHP
Flight PHP is very helpful to make
RESTful web services and
it is under MIT licence.
16
17. SYMFONY
Symfony is for highly professional developer
to build websites with PHP components
such as Drupal, PHPBB, laravel
eX, OROCRM and piwik.
17
19. LARAVEL
Laravel is most useful for RESRful Routing and
light weight bled tempting engine.
Laravel has integrated with some of great components
of well tested and reliable code.
19
20. ZEND
Zend is Modern frame work for
performing high end web applications.
This works based on Cryptographic
and secure coding tools.
20
21. CODEIGNITER
Codeigiter is simple to develop
small fool print for developer
who need simple and
elegant tool kit to create
innovative web applications.
21
22. PHALCON PHP
Pholcon PHP works based on MVC
and integrated with innovative
architecture to do perform faster.
22
27. 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
29. SCALAR DATA TYPE DESCRIPTION EXAMPLE
Integer A whole number 15
Float A floating - point number 8.23
String A series of characters “Hello, world!”
Boolean Represents either true or false true
29
30. FUNCTION DESCRIPTION
intval( value ) Returns value cast to an integer
floatval( value ) Returns value cast to a float
strval( value ) Returns value cast to a string
30
31. DATE AND TIME
Format String Description
B Swatch Internet Time — a time - zone - free, decimal time measure.
See http://en.wikipedia.org/wiki/Swatch_Internet_Time
for details
d Day of the month
h Hours (in 12 - hour format)
H Hours (in 24 - hour format)
i Minutes
I 1 if DST (Daylight Saving Time) is in effect, 0 otherwise
L 1 if the date is in a leap year, 0 otherwise
M Month number (1 – 12)
s Seconds
t The number of days in the month (28, 29, 30, or 31)
U The timestamp
w The day of the week, as a number (0 is Sunday)
W The week number within the year (counting from 1)
y The year as a two - digit number
Y The year as a four - digit number
z The day number within the year (0 is January 1)
Z The offset of the computer ’ s time zone from UTC (in seconds)
31
33. TYPE DESCRIPTION
Arithmetic Perform common arithmetical operations, such as addition and subtraction
Assignment Assign values to variables
Bitwise Perform operations on individual bits in an integer
Comparison Compare values in a Boolean fashion ( true or false is
returned)
Error Control Affect error handling
Execution Cause execution of commands as though they were shell
commands
Incrementing/Decrementing Increment or decrement a variable ’ s value
Logical Boolean operators such as and , or , and not that can be used to
include or exclude
String Concatenates (joins together) strings (there ’ s only one string
operator)
Array Perform operations on arrays (covered in Chapter 6 )
33
34. 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
35. 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
36. 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
37. 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
38. ESCAPE CHARACTERS
n A line feed character (ASCII 10)
r A carriage return character (ASCII 13)
t A horizontal tab character (ASCII 9)
v A vertical tab character (ASCII 11)
f A form feed character (ASCII 12)
A backslash (as opposed to the start of an escape sequence)
$ A $ symbol (as opposed to the start of a variable name)
” A double quote (as opposed to the double quote marking the end of a
string)
38
39. FUNCTION CASE - INSENSITIVE EQUIVALENT
strstr() stristr()
strpos() stripos()
strrpos() strripos()
str_replace() str_ireplace()
39
42. 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
43. 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
44. 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
50. 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
51. 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
52. 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
53. PROPERTIES
_get() is called whenever the calling code attempts to read an invisible
property of the object
_set() is called whenever the calling code attempts to write to an invisible
property of
the object
_call() is called whenever the calling code attempts to call an invisible
method of the object
53
54. 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
55. FILES READ AND WRITE
fread() — Reads a string of characters from a file
fwrite() — Writes a string of characters to a file
fgetc() — Reads a single character at a time
feof() — Checks to see if the end of the file has been reached
fgets() — Reads a single line at a time
fgetcsv() — Reads a line of comma - separated values
file() — Reads an entire file into an array
file_get_contents() — Reads an entire file into a string without needing to
open it
file_put_contents() — Writes a whole string to a file without needing to
open it
fpassthru() — Displays the contents of an open file
readfile() — Displays the contents of a file without needing to open it
fseek() — Moves the file pointer to a specific location within an open file
ftell() — Returns the position of the file pointer
rewind() — Moves the file pointer to the start of the file 55
57. 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
58. 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
59. DATABASE CONNECTIVITY
PHP is a server-side, HTML-embedded scripting language that may be used to create
dynamic Web
pages. It is available for most operating systems and Web servers, and can access most
common
databases, including MySQL. PHP may be run as a separate program or compiled as a
module for use
with a Web server.
59
60. PHP & MYSQL CONNECTIVITY
PHP provides three different MySQL API extensions:
• MySQL Improved Extension: Stands for “MySQL, Improved”; this extension is available
as of PHP 5.0.0. It is intended for use with MySQL 4.1.1 and later. This extension fully supports
the
authentication protocol used in MySQL 5.0, as well as the Prepared Statements and Multiple
Statements
APIs. In addition, this extension provides an advanced, object-oriented programming interface.
• MySQL Functions (PDO_MYSQL): Not its own API, but instead it's a MySQL driver for the
PHP database abstraction layer PDO (PHP Data Objects). The PDO MySQL driver sits in the
layer
below PDO itself, and provides MySQL-specific functionality. This extension is available as of
PHP 5.1.0.
• Original MySQL API: Available for PHP versions 4 and 5, this extension is intended for use
with MySQL versions prior to MySQL 4.1. This extension does not support the improved
authentication
protocol used in MySQL 4.1, nor does it support prepared statements or multiple statements.
To use
this extension with MySQL 4.1, you will likely configure the MySQL server to set the
60
61. DATABASE CONNECTIVITY
Selectphp.php
<html>
<head> <title>Welcome </title></head><body>
<h1>Hello It is time Renew! </h1>
<form name="Select" action="name_select.php" method="post">
Name: <input type="text" name="your_name" id="name" value="">
<input type="submit" value="submit">
</form>
Name_select.php
<?php
$con = mysql_connect('localhost','root','','mydbase');
if (!$con)
{
die('Could not connect: ' . mysql_error());
exit();
}
mysql_select_db("mydbase", $con);
$name = $_POST["name1"];
if($name)
{
$query = "SELECT customer_name,customer_id ,customer_email,customer_mbno FROM customers WHERE customer_name = '" . $name . "';";
61
62. DATABASE CONNECTIVITY
Selectphp.php
<html>
<head> <title>Welcome </title></head><body>
<h1>Hello It is time Renew! </h1>
<form name="Select" action="name_select.php" method="post">
Name: <input type="text" name="your_name" id="name" value="">
<input type="submit" value="submit">
</form>
Name_select.php
<?php
$con = mysql_connect('localhost','root','','mydbase');
if (!$con)
{
die('Could not connect: ' . mysql_error());
exit();
}
mysql_select_db("mydbase", $con);
$name = $_POST["name1"];
if($name)
{
$query = "SELECT customer_name,customer_id ,customer_email,customer_mbno FROM customers WHERE customer_name = '" . $name . "';";
62
68. 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
69. 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.
imagejpeg() outputs the image in JPEG format
imagegif() outputs the image in GIF format
imagepng() outputs the image in PNG format
69
70. IMAGES
imagejpeg() outputs the image in JPEG format
imagegif() outputs the image in GIF format
imagepng() outputs the image in PNG format
70
76. MONGO DB CONNECTION
Download and install xampp-win32-5.6.12-0-VC11-
installer.exe to C:xampp on Windows 7
Download http://windows.php.net/downloads/pecl/releases/mongo/1.6.11/p
hp_mongo-1.6.11-5.6-ts-vc11-x86.zip, extract php_mongo.dll and copy it
to C:xamppphpext
Add to C:xamppphpphp.ini line extension=php_mongo.dll
Copy C:xamppphplibsasl.dll to C:xamppapachebin, restart Apache and
enjoy.
76
77. 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
78. 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
79. REGULAR EXPRESSION
Matching strings against regular expressions: You explore PHP ’ s
preg_match() and preg_match_all() functions that let you apply regular
expressions to strings to
find matches.
The ins and outs of regular expression syntax: You learn all about the
special characters used in regular expressions, as well as how to match
character types, several characters at once, alternative groups of characters,
and much more.
Searching entire arrays of strings: You can use PHP ’ s preg_grep()
function to walk through an array of strings looking for text that matches a
regular expression.
Replacing text: You look at PHP ’ s preg_replace() and
preg_replace_callback()
functions for replacing matched text in a string with different text.
Pattern modifiers: You can make regular expressions even more flexible by
adding certain pattern modifiers to an expression.
Splitting strings: Just as you can use explode() to split a string using a fixed
delimiter, you can
use preg_split() to split strings based on regular expressions 79
80. PATTERN MATCHING
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
86. 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
87. 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>
<form action="" method="post" style="width: 30em;">
<div>
<input type="hidden" name="submitted" value="1" />
<label for="emailAddress">Your Email Address:</label>
<input type="text” name="emailAddress" id="emailAddress" value=""/>
<label for="phoneNumber">Your Phone Number:</label>
<input type="text” name="phoneNumber" id="phoneNumber" value=""/>
<label for="productCodes">Product Codes to Order:</label>
<input type="text" name="productCodes" id="productCodes" value=""/>
<label> </label>
<input type="submit" name="submitButton" value="Send Order"/>
</div>
</form>
<div style="clear: both;"> </div>
<p>(Separate product codes by commas. Codes are SW, MW, WW followed by 2
digits.)</p>
<?php
}
function processForm() {
$errorMessages = array();
$emailAddressPattern = "/
^ # Start of string
w+((-|.)w+)* # Some word characters optionally separated by - or
# .
@
[A-Za-zd]+ # Domain name: some alphanumeric characters
87
88. XML
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
89. XML
It is a subset of Standard Generalized Markup
Language (SGML, the parent of HTML). XML is
intended to allow different applications to exchange
data easily.
XML is a specification for creating your own markup
languages. In turn, you use these markup
languages to create documents. Like HTML, an XML
document contains elements and attributes in the
form of tags.
89
90. READING XML DOCUMENT WITH PHP
<?xml version="1.0" encoding="UTF-8"?>
<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
91. 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
92. 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
93. READING XML DOCUMENT WITH PHP
1.Reading, or parsing, XML documents using the XML Parser extension
2.Using the DOM extension to manipulate XML documents via the Document
Object Model
3. Reading, writing, and manipulating XML documents using PHP ’ s SimpleXML
extension
93
94. 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
96. XML DOCUMENT
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE stockList SYSTEM "http://127.0.0.1/dtds/stockList.dtd">
<stockList>
<item type="fruit">
<name>apple</name>
<unitPrice>0.99</unitPrice>
<quantity>412</quantity>
<description><![CDATA[Apples are >>>yummy<<<]]></description>
</item>
<item type="vegetable">
<name>beetroot</name>
<unitPrice>1.39</unitPrice>
<quantity>67</quantity>
<description><![CDATA[Beetroots are lovely & purple]]></description>
</item>
</stockList>?>
Sav as stock_list.xml
96
97. XML DOCUMENT
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE stockList SYSTEM "http://127.0.0.1/dtds/stockList.dtd">
<stockList>
<item type="fruit">
<name>apple</name>
<unitPrice>0.99</unitPrice>
<quantity>412</quantity>
<description><![CDATA[Apples are >>>yummy<<<]]></description>
</item>
<item type="vegetable">
<name>beetroot</name>
<unitPrice>1.39</unitPrice>
<quantity>67</quantity>
<description><![CDATA[Beetroots are lovely & purple]]></description>
</item>
</stockList>?>
Sav as stock_list.xml
97
98. XML DOCUMENT<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://127.0.0.1/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://127.0.0.1/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Parsing an XML File</title>
<link rel="stylesheet" type="text/css" href="common.css" />
</head>
<body>
<h1>Parsing an XML File</h1>
<pre>
<?php
/*
Start element handler:
Processes the start of an XML element, displaying the
element name as well as any attributes
*/
function startElementHandler( $parser, $element, $attributes )
{
echo "Start of element: "$element"";
if ( $attributes ) echo ", attributes: ";
foreach ( $attributes as $name => $value ) echo "$name=”$value" ";
echo "n";
}
/*
End element handler:
Processes the end of an XML element, displaying the
element name
98
99. UPLOAD PHOTO
<?php
if ( isset( $_POST["sendPhoto"] ) ) {
processForm();
} else {
displayForm();
}
function processForm() {
if ( isset( $_FILES["photo"] ) and $_FILES["photo"]["error"] ==
UPLOAD_ERR_OK ) {
if ( $_FILES["photo"]["type"] != "image/jpeg" ) {
echo "<p>JPEG photos only, thanks!</p>";
} elseif ( !move_uploaded_file( $_FILES["photo"]["tmp_name"],
"photos/" . basename( $_FILES["photo"]["name"] ) ) ) {
echo "<p>Sorry, there was a problem uploading that photo.</p>" .
$_FILES["photo"]["error"] ;
} else {
displayThanks();
}
} else {
switch( $_FILES["photo"]["error"] ) {
case UPLOAD_ERR_INI_SIZE:
$message = "The photo is larger than the server allows.";
break;
case UPLOAD_ERR_FORM_SIZE:
$message = "The photo is larger than the script allows.";
break;
case UPLOAD_ERR_NO_FILE:
$message = "No file was uploaded. Make sure you choose a file to
99
100. 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"
/></p>
100