THOUGHTS

**The youth needs to develop an attitude : I can do it! We can do it !! India will do it!!! ""மரங்களை நடுவோம் பசுமை இல்ல விளைவை தடுப்போம்"" !!! PLEASE DO IT**

Wednesday, August 10, 2011

PHP Tutorial Part 7


PHP XML DOM



The built-in DOM parser makes it possible to process XML documents in PHP.

What is DOM?

The W3C DOM provides a standard set of objects for HTML and XML documents, and a standard interface for accessing and manipulating them.

The W3C DOM is separated into different parts (Core, XML, and HTML) and different levels (DOM Level 1/2/3):

* Core DOM - defines a standard set of objects for any structured document
* XML DOM - defines a standard set of objects for XML documents
* HTML DOM - defines a standard set of objects for HTML documents

If you want to learn more about the XML DOM, please visit our XML DOM tutorial.


XML Parsing

To read and update - create and manipulate - an XML document, you will need an XML parser.
There are two basic types of XML parsers:
  • Tree-based parser: This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements
  • Event-based parser: Views an XML document as a series of events. When a specific event occurs, it calls a function to handle it
The DOM parser is an tree-based parser.
Look at the following XML document fraction:
<?xml version="1.0" encoding="ISO-8859-1"?>
<from>Jani</from>

The XML DOM sees the XML above as a tree structure:
  • Level 1: XML Document
  • Level 2: Root element: <from>
  • Level 3: Text element: "Jani"

Installation

The DOM XML parser functions are part of the PHP core. There is no installation needed to use these functions.

An XML File

The XML file below will be used in our example:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>


Load and Output XML

We want to initialize the XML parser, load the xml, and output it:

Example

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

print $xmlDoc->saveXML();
?>
The output of the code above will be:
Tove Jani Reminder Don't forget me this weekend!
If you select "View source" in the browser window, you will see the following HTML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The example above creates a DOMDocument-Object and loads the XML from "note.xml" into it.
Then the saveXML() function to puts the internal XML document into a string, so we can output it.

Looping through XML

We want to initialize the XML parser, load the XML, and loop through all elements of the <note> element:

Example

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
  {
  print $item->nodeName . " = " . $item->nodeValue . "<br />";
  }
?>
The output of the code above will be:
#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!
#text =
In the example above you see that there are empty text nodes between each element.
When XML generates, it often contains white-spaces between the nodes. The XML DOM parser treats these as ordinary elements, and if you are not aware of them, they sometimes cause problems.

 

 

 

 

 

 

PHP SimpleXML



SimpleXML handles the most common XML tasks and leaves the rest for other extensions.

What is SimpleXML?

SimpleXML is new in PHP 5. It is an easy way of getting an element's attributes and text, if you know the XML document's layout.
Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an element.
SimpleXML converts the XML document into an object, like this:
  • Elements - Are converted to single attributes of the SimpleXMLElement object. When there's more than one element on one level, they're placed inside an array
  • Attributes - Are accessed using associative arrays, where an index corresponds to the attribute name
  • Element Data - Text data from elements are converted to strings. If an element has more than one text node, they will be arranged in the order they are found
SimpleXML is fast and easy to use when performing basic tasks like:
  • Reading XML files
  • Extracting data from XML strings
  • Editing text nodes or attributes
However, when dealing with advanced XML, like namespaces, you are better off using the Expat parser or the XML DOM.

Installation

As of PHP 5.0, the SimpleXML functions are part of the PHP core. There is no installation needed to use these functions.

Using SimpleXML

Below is an XML file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
We want to output the element names and data from the XML file above.
Here's what to do:
1.    Load the XML file
2.    Get the name of the first element
3.    Create a loop that will trigger on each child node, using the children() function
4.    Output the element name and data for each child node
Example
<?php
$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "<br />";

foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child . "<br />";
  }
?>
The output of the code above will be:
note
to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!






PHP and AJAX

AJAX Introduction



AJAX = Asynchronous JavaScript And XML

AJAX is an acronym for Asynchronous JavaScript And XML.
AJAX is not a new programming language, but simply a new technique for creating better, faster, and more interactive web applications.
AJAX uses JavaScript to send and receive data between a web browser and a web server.
The AJAX technique makes web pages more responsive by exchanging data with the web server behind the scenes, instead of reloading an entire web page each time a user makes a change.

AJAX Is Based On Open Standards

AJAX is based on the following open standards:
  • JavaScript
  • XML
  • HTML
  • CSS
The open standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent. (Cross-Platform, Cross-Browser technology)

AJAX Is About Better Internet Applications

Web applications have many benefits over desktop applications:
  • they can reach a larger audience
  • they are easier to install and support
  • they are easier to develop
However, Internet applications are not always as "rich" and user-friendly as traditional desktop applications.
With AJAX, Internet applications can be made richer (smaller, faster, and easier to use).

 

 

You Can Start Using AJAX Today

There is nothing new to learn.
AJAX is based on open standards. These standards have been used by most developers for several years.
Most existing web applications can be rewritten to use AJAX technology instead of traditional HTML forms.

AJAX Uses XML And HTTP Requests

A traditional web application will submit input (using an HTML form) to a web server. After the web server has processed the data, it will return a completely new web page to the user.
Because the server returns a new web page each time the user submits input, traditional web applications often run slowly and tend to be less user friendly.
With AJAX, web applications can send and retrieve data without reloading the whole web page. This is done by sending HTTP requests to the server (behind the scenes), and by modifying only parts of the web page using JavaScript when the server returns data.
XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.
You will learn more about how this is done in the next chapters of this tutorial.

PHP and AJAX

There is no such thing as an AJAX server.
AJAX is a technology that runs in your browser. It uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.
AJAX is a web browser technology independent of web server software.
However, in this tutorial we will focus more on actual examples running on a PHP server, and less on how AJAX works.

 

 

 

 

 

AJAX XMLHttpRequest



The XMLHttpRequest object makes AJAX possible.

The XMLHttpRequest

The XMLHttpRequest object is the key to AJAX.
It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.

Creating An XMLHttpRequest Object

Different browsers use different methods to create an XMLHttpRequest object.
Internet Explorer uses an ActiveXObject.
Other browsers use a built in JavaScript object called XMLHttpRequest.
Here is the simplest code you can use to overcome this problem:
var XMLHttp=null;
if (window.XMLHttpRequest)
  {
  XMLHttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {
  XMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }




Example above explained:
1.    Create a variable named XMLHttp to use as your XMLHttpRequest object. Set the value to null.
2.    Test if the object window.XMLHttpRequest is available. This object is available in newer versions of Firefox, Mozilla, Opera, and Safari.
3.    If it's available, use it to create a new XMLHttpRequest object: XMLHttp=new XMLHttpRequest()
4.    If it's not available, test if the object window.ActiveXObject is available. This object is available in Internet Explorer version 5.5 and later.
5.    If it is available, use it to create a new object: XMLHttp=new ActiveXObject("Microsoft.XMLHTTP")

A Better Example?

Some programmers will prefer to use the newest and fastest version of the XMLHttpRequest object.
The example below tries to load Microsoft's latest version "Msxml2.XMLHTTP", available in Internet Explorer 6, before it falls back to "Microsoft.XMLHTTP", available in Internet Explorer 5.5 and later.
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}
Example above explained:
1.    First create a variable XMLHttp to use as your XMLHttpRequest object. Set the value to null.
2.    Try to create the object according to web standards (Mozilla, Opera and Safari):XMLHttp=new XMLHttpRequest()
3.    Try to create the object the Microsoft way, available in Internet Explorer 6 and later:XMLHttp=new ActiveXObject("Msxml2.XMLHTTP")
4.    If this catches an error, try the older (Internet Explorer 5.5) way: XMLHttp=new ActiveXObject("Microsoft.XMLHTTP")

PHP and AJAX Suggest



AJAX Suggest

In the AJAX example below we will demonstrate how a web page can communicate with a web server online as a user enters data into a web form.

Type a Name in the Box Below

First Name:
Suggestions:
This example consists of three pages:
  • a simple HTML form
  • a JavaScript
  • a PHP page

The HTML Form

This is the HTML page. It contains a simple HTML form and a link to a JavaScript:
<html>
<head>
<script src="clienthint.js"></script> 
</head>
<body>
<form> 
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p> 
</body>
</html>

Example Explained - The HTML Form

As you can see, the HTML page above contains a simple HTML form with an input field called "txt1".
The form works like this:
1.    An event is triggered when the user presses, and releases a key in the input field
2.    When the event is triggered, a function called showHint() is executed.
3.    Below the form is a <span> called "txtHint". This is used as a placeholder for the return data of the showHint() function.

The JavaScript

The JavaScript code is stored in "clienthint.js" and linked to the HTML document:
var xmlHttp;
 
function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("Browser does not support HTTP Request");
  return;
  } 
var url="gethint.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
} 
 
function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
 } 
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

Example Explained

The showHint() Function
This function executes every time a character is entered in the input field.
If there is some input in the text field (str.length > 0) the function executes the following:
1.    Defines the url (filename) to send to the server
2.    Adds a parameter (q) to the url with the content of the input field
3.    Adds a random number to prevent the server from using a cached file
4.    Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered
5.    Opens the XMLHTTP object with the given url.
6.    Sends an HTTP request to the server
If the input field is empty, the function simply clears the content of the txtHint placeholder.
The stateChanged() Function
This function executes every time the state of the XMLHTTP object changes.
When the state changes to 4 (or to "complete"), the content of the txtHint placeholder is filled with the response text. 
The GetXmlHttpObject() Function
AJAX applications can only run in web browsers with complete XML support.
The code above called a function called GetXmlHttpObject().
The purpose of the function is to solve the problem of creating different XMLHTTP objects for different browsers.
This is explained in the previous chapter.

The PHP Page

The server page called by the JavaScript code is a simple PHP file called "gethint.php".
The code in the "gethint.php" checks an array of names and returns the corresponding names to the client:
<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
  {
  if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
    {
    if ($hint=="")
      {
      $hint=$a[$i];
      }
    else
      {
      $hint=$hint." , ".$a[$i];
      }
    }
  }
}
 
//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
 
//output the response
echo $response;
?>
If there is any text sent from the JavaScript (strlen($q) > 0) the following happens:
1.    Find a name matching the characters sent from the JavaScript
2.    If more than one name is found, include all names in the response string
3.    If no matching names were found, set response to "no suggestion"
4.    If one or more matching names were found, set response to these names
5.    The response is sent to the "txtHint" placeholder

PHP and AJAX XML Example



AJAX can be used for interactive communication with an XML file.

AJAX XML Example

In the AJAX example below we will demonstrate how a web page can fetch information from an XML file using AJAX technology.

Select a CD in the Box Below

Select a CD:
CD info will be listed here.
This example consists of four pages:
  • a simple HTML form
  • an XML file
  • a JavaScript
  • a PHP page

 

 

 

 

 

 

 

 

 

 

 

 

The HTML Form

The example above contains a simple HTML form and a link to a JavaScript:
<html>
<head>
<script src="selectcd.js"></script>
</head>
<body>
<form> 
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<p>
<div id="txtHint"><b>CD info will be listed here.</b></div>
</p>
</body>
</html>

Example Explained

As you can see it is just a simple HTML form  with a simple drop down box called "cds".
The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for info retrieved from the web server.
When the user selects data, a function called "showCD" is executed. The execution of the function is triggered by the "onchange" event.
In other words: Each time the user changes the value in the drop down box, the function showCD is called.

The XML File

The XML file is "cd_catalog.xml". This document contains a CD collection.

 

 

 

 

 

 

 

 

The JavaScript

This is the JavaScript code stored in the file "selectcd.js":
var xmlHttp;
 
function showCD(str)
{ 
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request");
 return;
 } 
var url="getcd.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
 
function stateChanged() 
{ 
 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
 } 
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

Example Explained

The stateChanged() and GetXmlHttpObject functions are the same as in the last chapter, you can go to the previous page for an explanation of those
The showCD() Function
If an item in the drop down box is selected the function executes the following:
1.    Calls on the GetXmlHttpObject function to create an XMLHTTP object
2.    Defines the url (filename) to send to the server
3.    Adds a parameter (q) to the url with the content of the input field
4.    Adds a random number to prevent the server from using a cached file
5.    Call stateChanged when a change is triggered
6.    Opens the XMLHTTP object with the given url.
7.    Sends an HTTP request to the server

The PHP Page

The server paged called by the JavaScript, is a simple PHP file called "getcd.php".
The page is written in PHP using the XML DOM to load the XML document "cd_catalog.xml".
The code runs a query against the XML file and returns the result as HTML:
<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
  {
  if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
    { 
    $y=($x->item($i)->parentNode);
    }
  }
}
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++)
{ 
//Process only element nodes
if ($cd->item($i)->nodeType==1)
  { 
  echo($cd->item($i)->nodeName);
  echo(": ");
  echo($cd->item($i)->childNodes->item(0)->nodeValue);
  echo("<br />");
  } 
}
?>

 

 

 

Example Explained

When the query is sent from the JavaScript to the PHP page the following happens:
1.    PHP creates an XML DOM object of the "cd_catalog.xml" file
2.    All  "artist" elements (nodetypes = 1) are looped through to find a name matching the one sent from the JavaScript.
3.    The CD containing the correct artist is found
4.    The album information is output and sent to the "txtHint" placeholder

PHP and AJAX MySQL Database Example



AJAX can be used for interactive communication with a database.

AJAX Database Example

In the AJAX example below we will demonstrate how a web page can fetch information from a MySQL database using AJAX technology.

Select a Name in the Box Below

Select a User:

User info will be listed here.
This example consists of four elements:
  • a MySQL database
  • a simple HTML form
  • a JavaScript
  • a PHP page

The Database

The database we will be using in this example looks like this:
id
FirstName
LastName
Age
Hometown
Job
1
Peter
Griffin
41
Quahog
Brewery
2
Lois
Griffin
40
Newport
Piano Teacher
3
Joseph
Swanson
39
Quahog
Police Officer
4
Glenn
Quagmire
41
Quahog
Pilot

 

 

The HTML Form

The example above contains a simple HTML form and a link to a JavaScript:
<html>
<head>
<script src="selectuser.js"></script>
</head>
<body>
<form> 
Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<p>
<div id="txtHint"><b>User info will be listed here.</b></div>
</p>
</body>
</html>

Example Explained - The HTML Form

As you can see it is just a simple HTML form with a drop down box called "users" with names and the "id" from the database as option values.
The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for info retrieved from the web server.
When the user selects data, a function called "showUser()" is executed. The execution of the function is triggered by the "onchange" event.
In other words: Each time the user changes the value in the drop down box, the function showUser() is called.

The JavaScript

This is the JavaScript code stored in the file "selectuser.js":
var xmlHttp;
function showUser(str)
{ 
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request");
 return;
 }
var url="getuser.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
 } 
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

Example Explained

The stateChanged() and GetXmlHttpObject functions are the same as in the PHP AJAX Suggest chapter, you can go to there for an explanation of those.
The showUser() Function
If an item in the drop down box is selected the function executes the following:
1.    Calls on the GetXmlHttpObject function to create an XMLHTTP object
2.    Defines the url (filename) to send to the server
3.    Adds a parameter (q) to the url with the content of the dropdown box
4.    Adds a random number to prevent the server from using a cached file
5.    Call stateChanged when a change is triggered
6.    Opens the XMLHTTP object with the given url.
7.    Sends an HTTP request to the server

 

 

 

The PHP Page

The server page called by the JavaScript, is a simple PHP file called "getuser.php".
The page is written in PHP and uses a MySQL databse.
The code runs a SQL query against a database and returns the result as an HTML table:
<?php
$q=$_GET["q"];
 
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }
 
mysql_select_db("ajax_demo", $con);
 
$sql="SELECT * FROM user WHERE id = '".$q."'";
 
$result = mysql_query($sql);
 
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
 
while($row = mysql_fetch_array($result))
 {
 echo "<tr>";
 echo "<td>" . $row['FirstName'] . "</td>";
 echo "<td>" . $row['LastName'] . "</td>";
 echo "<td>" . $row['Age'] . "</td>";
 echo "<td>" . $row['Hometown'] . "</td>";
 echo "<td>" . $row['Job'] . "</td>";
 echo "</tr>";
 }
echo "</table>";
 
mysql_close($con);
?>

Example Explained

When the query is sent from the JavaScript to the PHP page the following happens:
1.    PHP opens a connection to a MySQL server
2.    The "user" with the specified name is found
3.    A table is created and the data is inserted and sent to the "txtHint" placeholder

No comments:

Post a Comment