kevinspence Posted March 13, 2010 Share Posted March 13, 2010 I'm working with XML parsing for the first time (thanks to CJ.com for making me learn something new!). Here is a simplified version of my XML doc: <item> <product>Product name</product> <manufacturer>Manufacturer name</manufacturer> </item> Now what I want to do is 'search' the XML doc by manufacturer and return the related products. Because my feed is rather large, I've been working with xmlReader, which seems to perform very well given the amount of data I'm throwing at it. Below is the code that I have so far. Basically, I'm looking at each manufacturer node, checking to see if the manufacturer is Sony, and then writing the manufacturer to the screen. Now what I need to do is return the name of the associated product -- only I cannot figure out how to get that value and assign it to a variable. Thanks in advance for your help! <?php $productList = array(); $i=0; $xmlReader = new XMLReader(); $xmlReader->open('myfeed.xml'); while($xmlReader->read()) { if ($xmlReader->localName == 'manufacturer'){ $xmlReader->read(); $productList[$i]['manufacturer'] = $xmlReader->value; if ($productList[$i]['manufacturer']=="Sony"){ echo $productList[$i]['manufacturer']; $i++; } } } ?> Link to comment https://forums.phpfreaks.com/topic/195072-xml-parsing-with-xmlreader/ Share on other sites More sharing options...
jacsdev Posted March 13, 2010 Share Posted March 13, 2010 Hi, Kevin, whats up? i saw your post in forum... well, i think you can solve that sutation with php xpath, in this way: Lets say, we have xml file named feed.xml, like this: feed.xml: <?xml version="1.0" encoding="UTF-8"?> <data> <item> <product>apple</product> <manufacturer>macbook</manufacturer> </item> <item> <product>mobile phone</product> <manufacturer>nokia</manufacturer> </item> <item> <product>vaio</product> <manufacturer>sony</manufacturer> </item> <item> <product>Play Station</product> <manufacturer>sony</manufacturer> </item> </data> So, we want extract all items that belong to sony manufacturer.. here the solution with php xpath: <?php // By @jacsdev $productList = array(); $xml = simplexml_load_file("feed.xml"); $result = $xml->xpath('/data/item[manufacturer="sony"]'); // this is query type called xpath, it mean: it seek every item where manufacture="sony" $i = 0; foreach($result as $item) { $productList[$i] = $item->product; // this give product name // note that item have: <product> and <manufacturer> tag, // so in this case we could to get respective values with $item->product and $item->manufacturer // ouput echo $productList[$i]; echo "<br>"; $i++; } ?> Link to comment https://forums.phpfreaks.com/topic/195072-xml-parsing-with-xmlreader/#findComment-1025501 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.