XML — Parsers, SimpleXML, Expat & DOM
XML stores structured data in tags. PHP can read XML with SimpleXML (easy), XML Parser (Expat, event-based), or DOMDocument (full tree).
XML Parsers overview
XML stores structured data in tags. PHP can read XML with SimpleXML (easy), XML Parser (Expat, event-based), or DOMDocument (full tree).
Real-life example: XML is a labeled packing list — each <item> tag describes one product in the shipment.
<?xml version="1.0" encoding="UTF-8"?>
<courses>
<course id="1">
<title>PHP Fundamentals</title>
<lessons>32</lessons>
</course>
<course id="2">
<title>MySQL Basics</title>
<lessons>20</lessons>
</course>
</courses>SimpleXML
simplexml_load_file() or simplexml_load_string() turns XML into an object you can traverse with -> and foreach.
Real-life example: SimpleXML is reading a short menu — quick glance, pick items by name.
<?php
$xml = simplexml_load_string('<?xml version="1.0"?><root><name>Rishtaara</name></root>');
echo $xml->name;
$books = simplexml_load_file("courses.xml");
foreach ($books->course as $course) {
echo (string) $course->title . "\n";
}
?>XML Parser (Expat) and DOM
xml_parser_create() (Expat) fires callbacks on start/end tags — memory efficient for huge files. DOMDocument builds a full editable tree.
Real-life example: Expat is a conveyor belt — items pass one at a time. DOM is spreading the whole puzzle on a table to move pieces.
<?php
$dom = new DOMDocument();
$dom->load("courses.xml");
$titles = $dom->getElementsByTagName("title");
foreach ($titles as $node) {
echo $node->textContent . "\n";
}
?><?php
$parser = xml_parser_create();
xml_parse_into_struct($parser, file_get_contents("courses.xml"), $values);
xml_parser_free($parser);
print_r($values);
?>