AJAX XML

PHP AJAX and XML

AJAX originally became famous for its ability to fetch and parse XML files (hence the "X" in AJAX). While JSON is far more popular today, knowing how to process XML dynamically is still a highly sought-after skill, especially when dealing with older enterprise APIs or RSS feeds.


Creating an XML Reader

Let's build an application that lets a user select a CD title from a dropdown menu. When a title is clicked, AJAX will query the server to find that specific CD inside an XML catalog and display its information.

1. The PHP Script (getcd.php)

When the AJAX request reaches the server, we will use PHP's built-in DOM parser to read a file called cd_catalog.xml.

<?php
$q = $_GET["q"];

// Initialize the XML DOM Parser $xmlDoc = new DOMDocument(); $xmlDoc->load("cd_catalog.xml");

// Get all elements with the tag 'ARTIST' $x = $xmlDoc->getElementsByTagName('ARTIST');

// Loop through the XML elements to find the match for ($i = 0; $i <= $x->length - 1; $i++) { // Process elements that are valid nodes if ($x->item($i)->nodeType == 1) { if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {

  // Once found, navigate up to the parent node (the CD itself)
  $y = ($x-&gt;item($i)-&gt;parentNode);
}

} }

// Extracting sibling data (like Title and Price) $cd = ($y->childNodes);

for ($i = 0; $i < $cd->length; $i++) { // Only output valid element nodes if ($cd->item($i)->nodeType == 1) { echo "<b>" . $cd->item($i)->nodeName . ":</b> "; echo $cd->item($i)->childNodes->item(0)->nodeValue; echo "<br>"; } } ?>

How It Works

  1. PHP loads the massive cd_catalog.xml file into the server's memory.
  2. It searches the entire file specifically for the ARTIST name sent by the AJAX ?q= parameter.
  3. Once it finds the artist, it pulls all related details (Price, Year, Title) and formats them into nice, readable HTML.
  4. The formatted HTML is sent back to the browser instantly!

Exercise

?

What is the primary role of PHP when handling an AJAX request for XML data?