AJAX and PHP 5 both have powerful features for processing and using an XML document. XML is a method of formatting data often for communication purposes between different computer systems. In this article, we will show you how to access an XML document with AJAX!
Basically the AJAX client-browser and the PHP server can communicate any kind of data (except images and binary) by means of XML documents. Part 1 of this series on AJAX and PHP showed the basics of AJAX communication, and if you are not familiar with AJAX you should read Part 1. This article will focus on processing requested XML data within the client-browser, and we will touch on the PHP server side XML processing as well. This tutorial will primarily focus on the client-browser use of XML received from a server by means of AJAX; this is the most common use of XML with AJAX. Sending requests to a PHP server script is usually in the form of a GET or POST method, but for a client-browser to receive many fields of organized information, one can use XML as we will demonstrate.
You can download the complete working example of this tutorial here.
PHP Script Handling of XML
The following example script could be saved in a file called getxml.php or what ever you want to name it, this would read an XML document file called somedoc.xml and print the XML as a response to an AJAX request. Our AJAX example will use the following PHP script and the XML data following that in Listing B. Note that any PHP script producing XML data must set the response header to an XML type, as we have done with the header( ) statement in Listing A. This PHP script simply reads the XML file and prints it to the browser.
Listing A: PHP script 'getxml.php'
<?
header('content-type: application/xhtml+xml; charset=utf-8');

$dom = new DomDocument('1.0');
$dom->load("somedoc.xml");  //load XML from local file

print $dom->saveXML();   //outputs the XML as response to client
?>
Using PHP you can also access XML elements of DOM object variables, the $dom variable in this case, with PHP commands like the following:
<?
$titles = $dom->getElementsByTagName("title");
foreach($titles as $node) {
   print $node->textContent." ";
}
?>
Listing B: XML file 'somedoc.xml' contents
<?xml version="1.0" encoding="iso-8859-1" ?>

<response>

<cell>
<title>Title AAA</title>
<description>This is AAA's description</description>
</cell>

<cell>
<title>Title BBB</title>
<description>This is BBB's description</description>
</cell>

<cell>
<title>Title CCC</title>
<description>This is CCC's description</description>
</cell>

</response>
AJAX Processing of XML
AJAX is an advanced feature of JavaScript primarily programmed within client-browser pages; any server-side programmable language can support it. JavaScript has what is called the DOM or Document Object Model for programming--it is used for XML processing. We will use the DOM methods .getElementsByTagName( ) and .childNodes[ ].value in this tutorial, as these are the methods that allow the client-browser to process XML documents that are received via AJAX.
Listing C: HTML/JavaScript page utilizing XML requests
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>

<title>Advanced AJAX Part 1</title>

<script language="javascript"  type="text/javascript">

function processXML(xmlDoc) {  //process the received XML data with DOM methods
   try {
	var cells = xmlDoc.getElementsByTagName("cell");
      for (var x=0; x<cells.length; x++) {
        var title = cells[x].getElementsByTagName("title")[0].firstChild.nodeValue;
        var desc = cells[x].getElementsByTagName("description")[0].firstChild.nodeValue;
	  //Following lines place the data into our HTML page table
	  var cid = "cell"+(x+1);
	  document.getElementById(cid).innerHTML = title+"<br>"+desc;
      }
   } catch (e) {
	alert("Error:"+e.name+"\n"+e.message);
   }
}


function doHttpRequest() {  // This function does the AJAX request
  http.open("GET", "getxml.php", true);
  http.onreadystatechange = getHttpRes;
  http.send(null);
}


function getHttpRes() {
  try {
    if (http.readyState == 4 ) { 
        if (http.status == 200) {
		var xmlres = http.responseXML.documentElement;  //This gets the XML response
	    	processXML(xmlres); //processXML() uses the XML by populating an HTML table
        } else {
            alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
    }
  } catch (e) {
	alert("Error:"+e.name+"\n"+e.message);
  }
}



function getXHTTP() {
  var xhttp;
   try {   // The following blocks get the XMLHTTP object for various browsers
      xhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
 		 // This block handles Mozilla/Firefox browsers...
	    try {
	      xhttp = new XMLHttpRequest();
	    } catch (e3) {
	      xhttp = false;
	    }
      }
    }
  return xhttp; // Return the XMLHTTP object
}

var http = getXHTTP(); // This executes when the page first loads.

</script>

</head>

<body>

<input type="button" value="Press" name="btn" onClick="doHttpRequest();">

<br><br><br>

XML data...

<table width=100% border=1 cellspacing=0>
   <tr><td id="cell1">cell1</td> <td id="cell2">cell2</td> <td id="cell3">cell3</td><tr>
</table>

</body>
</html>
Our HTML/JavaScript page above could be saved as index.html or mypage.html or it could even be a PHP page. The AJAX features are all standard but you should notice the following line within the getHttpRes( ) function above. This gets the AJAX response from the server into the xmlres variable, but as an XML document, not as just Text.
var xmlres = http.responseXML.documentElement;
The xmlres variable becomes a type XML DOM object. This xmlres variable is passed to the processXML( ) function which processes the various tags and contents in the XML document, examine this function.
function processXML(xmlDoc) {  //process the received XML data with DOM methods
   try {
	var cells = xmlDoc.getElementsByTagName("cell");
      for (var x=0; x<cells.length; x++) {
        var title = cells[x].getElementsByTagName("title")[0].firstChild.nodeValue;
        var desc = cells[x].getElementsByTagName("description")[0].firstChild.nodeValue;
	  //Following lines place the data into our HTML page table
	  var cid = "cell"+(x+1);
	  document.getElementById(cid).innerHTML = title+"<br>"+desc;
      }
   } catch (e) {
	alert("Error:"+e.name+"\n"+e.message);
   }
}
Notice the 2nd line document.getElementById(cid).innerHTML, this does dynamic updating of the cells of our HTML table using the <title> and <description> fields of the XML document variable passed to the above function as xmlDoc. You can break up an XML document into a set of elements as we do in this line of our above function: var cells = xmlDoc.getElementsByTagName("cell"); This creates another XML document variable named cells which holds all the "cell" elements of the original XML document shown in Listing B.
We hope you have enjoyed the topic and found this tutorial educational. Look for more tutorials in this AJAX and PHP series of articles coming soon!