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.
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 :
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.
user-data.xml
This file consists of xml tags.
<?xml version="1.0" encoding="UTF-8"?> <employees> <employee joindate="12/11/2007"> <username> Sumit Kumar Pradhan </username> <empid> 29377493 </empid> <age> 34 </age> <salary> 333339</salary> </employee> <employee joindate="01/11/2017"> <username> Amit Kumar </username> <empid> 15454545 </empid> <age> 23 </age> <salary> 256454</salary> </employee> </employees>
XMLReader-example.php
We are going to read above XML file using this script.
<?php $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>"; } } $reader->close(); ?>
Output:
12/11/2007
Sumit Kumar Pradhan
29377493
34
01/11/2017
Amit Kumar
15454545
23
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