PHP XML Reader

by Vincy. Last modified on July 14th, 2022.

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.

XML Reader Features

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

  • Retrieving portion of an XML document based on the 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 the 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 the whole XML into memory.
  • It can parse large and high complex XML documents having more sub-trees.

PHP XML Reader Example

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

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page