Because I will be parsing a very large XML file, I am trying to use XMLReader to retrieve the XML data, and use simpleXML to display. I have never used XMLreader, so I am simply trying to get a basic feel for using XMLReader. I want to display all the name and price values in the XML file, and I cannot get this code to display anything. Am I missing something?
Here is the XMLReader/simpleXML code:
$z = new XMLReader;
$z->open('products.xml');
$doc = new DOMDocument;
while ($z->read() && $z->name === 'product') {
$node = simplexml_import_dom($doc->importNode($z->expand(), true));
var_dump($node->name);
$z->next('product');
}
Here is the XML file, named products.xml:
<products>
<product category="Desktop">
<name> Desktop 1 (d)</name>
<price>499.99</price>
</product>
<product category="Tablet">
<name>Tablet 1 (t)</name>
<price>1099.99</price>
</product>
</products>
Your loop condition is broken. You loop if you get an element AND that elements name is "
product
". The document element is "products
", so the loop condition is neverTRUE
.You have to be aware that
read()
andnext()
are moving the internal cursor. If it is on a<product>
node,read()
will move it to the first child of that node.Output: