AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 153


PART I


<votes id=\"votes\">$votes</votes>
</pollresults>";

echo $message;

While this is the most direct method to create an XML response, you might instead
employ DOM features of your server-side framework instead, as demonstrated here:

header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: text/xml");
$xml = new DOMDocument('1.0', 'UTF-8');
$root = $xml->createElement("pollresults");
$ratingNode = $xml->createElement("rating");
$ratingNode->appendChild($xml->createTextNode($rating));
$ratingNode->setAttribute("id", "rating");
$root->appendChild($ratingNode);
$averageNode = $xml->createElement("average");
$averageNode->appendChild($xml->createTextNode($average));
$averageNode->setAttribute("id", "average");
$root->appendChild($averageNode);
$votesNode = $xml->createElement("votes");
$votesNode->appendChild($xml->createTextNode($votes));
$votesNode->setAttribute("id", "votes");
$root->appendChild($votesNode);
$xml->appendChild($root);
$message = $xml->saveXML();
echo $message;

Depending on your application architecture, you may even have XML packets formed
directly by printing the results of queries to your back-end datastore. This is a bit beyond
what we are talking about here, and regardless of how the XML is created, it will look the
same across the wire:
Free download pdf