Reading XML file with PHP, XML file is not organized
Hi all I have an XML file like this:
<?xml version="1.0"?>
<catalog>
<car>
<title>This is car</title>
<price>44.95</price>
<model>2018</model>
<description>An in-depth look at creating applications with XML.</description>
</car>
<bike>
<title>this is bike</title>
<price>33.58</price>
<description>Just the dummy description</description>
</bike>
<wheels>
<title>this is wheel</title>
<price>33.58</price>
<description>Just the dummy description</description>
</wheels>
<bike>
<title>this is bike</title>
<price>33.58</price>
<description>Just the dummy description</description>
</bike>
</catalog>
I want to loop through the nodes and process the nodes accordingly. If it's a car, I need to pass the car details to some function and if it's a bike then I need to pass the bike details to the other function.
The point is to process the nodes based on the node type (car or bike or other).
PHP
$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');
}
The above PHP code works fine if the nodes are products. I need to work with different nodes.
Answer
Solution:
You can do this just using SimpleXML:
Output (for your sample XML)
Demo on 3v4l.org