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.
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.
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->item($i)->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>"; } } ?>
cd_catalog.xml file into the server's memory.?q= parameter.What is the primary role of PHP when handling an AJAX request for XML data?