XML Reader extension is used to create an XML parser to walk through an XML document. This is the last one among the list of PHP core XML parsing techniques we have seen. This parser is referred to as a stream-based XML parser and is also called a pull parser.
Before PHP version 5.1.0, XML Reader extension was part of PECL extension. So, we need to install PECL and enable XML Reader to use its functions. Later, it was added to PHP core and enabled by default.
PHP XML Reader extension contains many features and some of these are,
XML Reader is a good choice to parse XML if we want to do stream-based parsing. Because
In this example, we load the given XML document for the parser handler created by XMLReader class. This parser reads XML elements by iterating over a loop.
In each iteration, the parser checks if the current node is <toy>. If so, it prints the ID attribute and inner XML of the current node. At the end of iteration, next() is used to jump next <toy> node by skipping current <toy> node’s sub-elements.
<?php
$xmlDocument = '<?xml version="1.0"?>
<toys>
<toy code="10001">
<name>Ben 10 Watch</name>
<type>Battery Toys</type>
</toy>
<toy code="10002">
<name>Angry Birds Gun</name>
<type>Mechanical Toys</type>
</toy>
</toys>';
$xml = new XMLReader();
$xml->XML($xmlDocument);
while ($xml->read()) {
if ($xml->name == "toy") {
print "ID:" . $xml->getAttribute("code") . "<br/>";
print $xml->readInnerXML() . "<br/>";
$xml->next();
}
}
?>
This program will result in the markup,
ID:10001
<name>Ben 10 Watch</name>
<type>Battery Toys</type>
ID:10002
<name>Angry Birds Gun</name>
<type>Mechanical Toys</type>
Download PHP XML Reader Source Code