I build a XML file as bellow, in which main "list" tag contain all data. There are multiple categories and each category have its multiple products.
I'm creating a PHP script to parse and show products category wise. See the script bellow. It's getting difficult for me to categorize each product.
I need to show each product just bellow its category, but it's showing all products. How can I filter each product category wise?
<?xml version="1.0" encoding="ISO-8859-1"?>
<list>
<category>
<catname>PC</catname>
<game>
<gamename>Game1</gamename>
<id>001</id>
<desc>some desc of game1.</desc>
</game>
<game>
<gamename>Game2</gamename>
<id>002</id>
<desc>some desc of game2.</desc>
</game>
</category>
<category>
<catname>MAC</catname>
<game>
<gamename>Game3</gamename>
<id>003</id>
<desc>some desc of game3.</desc>
</game>
<game>
<gamename>Game4</gamename>
<id>004</id>
<desc>some desc of game4.</desc>
</game>
</category>
</list>
Here is PHP code I'm using,
<?php
$XML = new DOMDocument();
libxml_use_internal_errors(true);
$XML->load("test.xml");
if(!$XML){
echo "can not load XML file";
exit();
}
$category = $XML->getElementsByTagName("category");
foreach( $category as $value ){
$Names = $value->getElementsByTagName("catname");
$Name = $Names->item(0)->nodeValue;
echo $Name . "<br />";
$game = $XML->getElementsByTagName("game");
// second loop to get value inside game tag
foreach( $game as $value2 ){
$gamenames = $value2->getElementsByTagName("gamename");
$gamename = $gamenames->item(0)->nodeValue;
echo $gamename . "<br />";
}
}
?>
Here is output I'm getting
PC
Game1
Game2
Game3
Game4
MAC
Game1
Game2
Game3
Game4
But I want to show,
PC
Game1
Game2
MAC
Game1
Game2
Am I not looping properly or is there other method to parse this type of XML structure.
Thank You!