PHP XML Reader

XML Reader extension is used to create XML parser to walk through a XML document. This is the last one among the list of PHP core XML parsing techniques we have seen. This parser is referred as stream based XML parser and also called as 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 into PHP core and enabled by default.

data_stream

XML Reader Features

PHP XML Reader extension contains many features and some of these are,

  • Retrieving portion of XML document based on current node.
  • Getting attributes based on index, name or namespace.
  • Parsing elements based on attribute’s index, name or namespace.
  • Parsing elements in current depth without stepping into inner levels.
  • Getting current node’s value.
  • Setting additional  properties/options to XML parser.
  • Validating XML document.

XML Reader Advantages

XML Reader is a good choice to parse XML, if we want to do stream based parsing. Because,

  • It is faster, since it is not loading whole XML into memory.
  • It can parse large and high complex XML document having more sub-trees.

PHP XML Reader Example

In this example, we load the given XML document for parser handler created by XMLReader class. This parser reads XML elements by iterating over a loop. In each iteration, the parser checks if 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 with 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

This PHP code tutorial was published on November 19, 2013.

↑ Back to Top