#native_company# #native_desc#
#native_cta#

AJAX and PHP Part 2: XML Communication/Processing

By Jon Campbell
on June 28, 2007

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>