Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

user-data.xml
This file consists of xml tags.
xml version="1.0" encoding="UTF-8"?>


joindate="12/11/2007">
Sumit Kumar Pradhan
29377493
34
333339


joindate="01/11/2017">
Amit Kumar
15454545
23
256454




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
"
"
;
//get employee join date
echo $address
= $reader->getAttribute('joindate')."
"
;
// get username
echo $node
->username."
"
;
// get employee id
echo $node
->empid."
"
;
// get employee age
echo $node
->age."
"
;
//get employee salary

echo
"
";

}
}
$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 :
https://github.com/skptricks/php-Tutorials/tree/master/PHP%20XML%20Reader%20Example





This post first appeared on PHP Update Data In MySQL Database, please read the originial post: here

Share the post

PHP XML Reader Example

×

Subscribe to Php Update Data In Mysql Database

Get updates delivered right to your inbox!

Thank you for your subscription

×