Monday, April 23, 2018

PHP XML Reader Example

Today, In this tutorial we are going to learn how to parse an large XML file using XMLReader Class. The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.
PHP XML Reader Example, PHP XMLReader Example

The XMLReader extension was initially a PECL extension for PHP 5. It was later moved to the PHP source bundled as of PHP 5.1.0, and later enabled by default as of PHP 5.1.2

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

XML Reader Features:
  • 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.
  • Validating XML document

Lets see the example where we are going to parse an xml tag from the external source file. Here we are using XMLReader to get to each node, then use SimpleXML to access them. This way, you keep the memory usage low because you're treating one node at a time and you still leverage SimpleXML's ease of use.

This file consists of xml tags.
<?xml version="1.0" encoding="UTF-8"?>
<employee joindate="12/11/2007">
  <username> Sumit Kumar Pradhan </username>
  <empid> 29377493 </empid>
  <age> 34 </age>
  <salary> 333339</salary>

<employee joindate="01/11/2017">
  <username> Amit Kumar </username>
  <empid> 15454545 </empid>
  <age> 23 </age>
  <salary> 256454</salary>


We are going to read above XML file using this script.

$reader = new XMLReader();

$doc = new DOMDocument;

// read file external xml file...
if (!$reader->open("user-data.xml")) {
    die("Failed to open 'user-data.xml'");

// reading xml data...
while($reader->read()) {
  if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'employee') {
    $node = simplexml_import_dom($doc->importNode($reader->expand(), true));
          echo "<pre>";
         //get employee join date
         echo $address = $reader->getAttribute('joindate')."<br/>";   
 // get username
        echo $node->username."<br/>";
 // get employee id
 echo $node->empid."<br/>";
 // get employee age
 echo $node->age."<br/>";
 //get employee salary 
 echo "</pre>";


 Sumit Kumar Pradhan 
 Amit Kumar 

This is all about PHP XML Reader Example. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

Download link :

No comments:

Post a Comment