While modern web APIs predominantly exchange JSON, XML (Extensible Markup Language) remains deeply entrenched in enterprise software, government portals, Google XML Sitemaps (sitemap.xml), and RSS news feeds. PHP provides native, high-performance XML parsers, most notably SimpleXML (for fast, intuitive reading) and DOMDocument (for deep structural manipulation).
simplexml_load_string)<?php
$xmlData = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<course id="101">
<title>PHP 8 Web Development</title>
<faculty>Dr. Sharma</faculty>
<fee>4500</fee>
</course>
<course id="102">
<title>Database Systems with PDO</title>
<faculty>Prof. Verma</faculty>
<fee>5000</fee>
</course>
</catalog>
XML;
// Load XML string into a SimpleXML object
$xml = simplexml_load_string($xmlData);
echo "<ul>";
foreach ($xml->course as $c) {
// Accessing XML attributes and child tags directly!
echo "<li>Course ID #" . $c['id'] . ": <b>" . $c->title . "</b> (Faculty: " . $c->faculty . ") - Fee: ₹" . $c->fee . "</li>";
}
echo "</ul>";
?>
You can read an external XML sitemap or blog RSS feed directly from a file or web URL using simplexml_load_file():
<?php
// Reading an external XML file
if (file_exists("sitemap.xml")) {
$sitemap = simplexml_load_file("sitemap.xml");
foreach ($sitemap->url as $urlBlock) {
echo "Indexed URL: " . $urlBlock->loc . "<br>";
}
}
?>
High-Frequency Exam Question:
Q: How do you access XML tag attributes in SimpleXML?
A: In SimpleXML, XML child elements are accessed as object properties ($xml->childTag), whereas XML element attributes are accessed using array square bracket notation ($xml->childTag['attributeName']).
Exercise 45.1: Create a valid XML file named books.xml with 3 books (title, author, price). Write a PHP script that loads and displays them in an HTML table.
Exercise 45.2: Write a script that converts a SimpleXML object into JSON using json_encode($xml).