It all depends on how big the unit of work, but I guess you're trying to treat each <product/> nodes in succession.

For that, the simplest way would be to use 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. For instance:

$z = new XMLReader;
$z->open('data.xml');

$doc = new DOMDocument;

// move to the first <product /> node
while ($z->read() && $z->name !== 'product');

// now that we're at the right depth, hop to the next <product/> until the end of the tree
while ($z->name === 'product')
{
    // either one should work
    //$node = new SimpleXMLElement($z->readOuterXML());
    $node = simplexml_import_dom($doc->importNode($z->expand(), true));

    // now you can use $node without going insane about parsing
    var_dump($node->element_1);

    // go to next <product />
    $z->next('product');
}

Quick overview of pros and cons of different approaches:

XMLReader only

  • Pros: fast, uses little memory

  • Cons: excessively hard to write and debug, requires lots of userland code to do anything useful. Userland code is slow and prone to error. Plus, it leaves you with more lines of code to maintain

XMLReader + SimpleXML

  • Pros: doesn't use much memory (only the memory needed to process one node) and SimpleXML is, as the name implies, really easy to use.

  • Cons: creating a SimpleXMLElement object for each node is not very fast. You really have to benchmark it to understand whether it's a problem for you. Even a modest machine would be able to process a thousand nodes per second, though.

XMLReader + DOM

  • Pros: uses about as much memory as SimpleXML, and XMLReader::expand() is faster than creating a new SimpleXMLElement. I wish it was possible to use simplexml_import_dom() but it doesn't seem to work in that case

  • Cons: DOM is annoying to work with. It's halfway between XMLReader and SimpleXML. Not as complicated and awkward as XMLReader, but light years away from working with SimpleXML.

My advice: write a prototype with SimpleXML, see if it works for you. If performance is paramount, try DOM. Stay as far away from XMLReader as possible. Remember that the more code you write, the higher the possibility of you introducing bugs or introducing performance regressions.

Answer from Josh Davis on Stack Overflow
🌐
PHP
php.net › manual › en › book.xmlreader.php
PHP: XMLReader - Manual
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.
🌐
GitHub
github.com › kiwilan › php-xml-reader
GitHub - kiwilan/php-xml-reader: PHP package to read XML with nice API. · GitHub
use Kiwilan\XmlReader\XmlReader; $xml = XmlReader::make('path/to/file.xml', bool $mapContent = true, bool $failOnError = true);
Author   kiwilan
Top answer
1 of 7
239

It all depends on how big the unit of work, but I guess you're trying to treat each <product/> nodes in succession.

For that, the simplest way would be to use 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. For instance:

$z = new XMLReader;
$z->open('data.xml');

$doc = new DOMDocument;

// move to the first <product /> node
while ($z->read() && $z->name !== 'product');

// now that we're at the right depth, hop to the next <product/> until the end of the tree
while ($z->name === 'product')
{
    // either one should work
    //$node = new SimpleXMLElement($z->readOuterXML());
    $node = simplexml_import_dom($doc->importNode($z->expand(), true));

    // now you can use $node without going insane about parsing
    var_dump($node->element_1);

    // go to next <product />
    $z->next('product');
}

Quick overview of pros and cons of different approaches:

XMLReader only

  • Pros: fast, uses little memory

  • Cons: excessively hard to write and debug, requires lots of userland code to do anything useful. Userland code is slow and prone to error. Plus, it leaves you with more lines of code to maintain

XMLReader + SimpleXML

  • Pros: doesn't use much memory (only the memory needed to process one node) and SimpleXML is, as the name implies, really easy to use.

  • Cons: creating a SimpleXMLElement object for each node is not very fast. You really have to benchmark it to understand whether it's a problem for you. Even a modest machine would be able to process a thousand nodes per second, though.

XMLReader + DOM

  • Pros: uses about as much memory as SimpleXML, and XMLReader::expand() is faster than creating a new SimpleXMLElement. I wish it was possible to use simplexml_import_dom() but it doesn't seem to work in that case

  • Cons: DOM is annoying to work with. It's halfway between XMLReader and SimpleXML. Not as complicated and awkward as XMLReader, but light years away from working with SimpleXML.

My advice: write a prototype with SimpleXML, see if it works for you. If performance is paramount, try DOM. Stay as far away from XMLReader as possible. Remember that the more code you write, the higher the possibility of you introducing bugs or introducing performance regressions.

2 of 7
14

For xml formatted with attributes...

data.xml:

<building_data>
<building address="some address" lat="28.902914" lng="-71.007235" />
<building address="some address" lat="48.892342" lng="-75.0423423" />
<building address="some address" lat="58.929753" lng="-79.1236987" />
</building_data>

php code:

$reader = new XMLReader();

if (!$reader->open("data.xml")) {
    die("Failed to open 'data.xml'");
}

while($reader->read()) {
  if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'building') {
    $address = $reader->getAttribute('address');
    $latitude = $reader->getAttribute('lat');
    $longitude = $reader->getAttribute('lng');
}

$reader->close();
🌐
W3Schools
w3schools.com › php › php_xml_simplexml_read.asp
PHP SimpleXML Parser
This parser provides an easy way to access elements, attributes and textual content of an XML document. Tip: The SimpleXML Parser is a part of the PHP core.
🌐
GitHub
github.com › saloonphp › xml-wrangler
GitHub - saloonphp/xml-wrangler: 🌵 XML Wrangler - Easily Read & Write XML in PHP
You can use the elements and values methods to convert the whole XML document into an array. If you would like an array of values, use the values method - but if you need to access attributes on the elements, the elements method will return an array of Element DTOs. $reader = XmlReader::fromString(...); $elements = $reader->elements(); // Array of `Element::class` DTOs $values = $reader->values(); // Array of values.
Starred by 420 users
Forked by 15 users
Languages   PHP 100.0% | PHP 100.0%
🌐
PHPpot
phppot.com › php › php-xml-reader
PHP XML Reader - PHPpot
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.
🌐
Tutorialspoint
tutorialspoint.com › php › php_function_xmlreader_read.htm
PHP - XMLReader::read() Function
<?php //Creating an XMLReader $reader = new XMLReader(); //Opening a reader $reader->open("test.xml"); //Reading the contents of XML document $reader->read(); $reader->read(); $reader->next("phone"); //Reading the contents print($reader->name."\n"); ...
🌐
W3Schools
w3schools.com › php › php_xml_parsers.asp
PHP XML Parsers
Examples of event-based parsers: XMLReader and XML Expat Parser. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › php tutorial › php xml reader
PHP XML Reader | Working of Xml Reader in PHP with Examples
July 3, 2023 - In PHP, the XML Reader extension provides a technique for parsing XML called the XML Reader. This pull-parser or stream-based XML parser allows for creating an XML parser that can read and retrieve specific parts of an XML document.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Laravel News
laravel-news.com › home › laravel packages › easily read and write xml in php
Easily Read and Write XML in PHP - Laravel News
November 3, 2023 - <?php · use Saloon\XmlWrangler\XmlReader; $reader = XmlReader::fromString($xml); // Retrieve all values as one simple array · $reader->values(); // ['breakfast_menu' => [['name' => '...'], ['name' => '...'], ...] // Use dot-notation to find a specific element ·
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-xmlreader-xml-function
PHP | XMLReader XML() Function - GeeksforGeeks
March 18, 2020 - <?php // Create a new XMLReader instance $XMLReader = new XMLReader(); $XML = "<?xml version=\"1.0\"?> <div> <p> GeeksforGeeks </p> </div>"; // Open the XML file $XMLReader->XML($XML); // Iterate through the XML nodes while ($XMLReader->read()) { if ($XMLReader->nodeType == XMLREADER::ELEMENT) { echo "We are at " .