I am trying to read the xml from a file and display them just like a tree. I am using PHP and I want to get the output as shown below. The content of xml file is as follows…
<Categories>
<Category>
<Id>1</Id>
<Name>Parent 1</Name>
<ParentId>1</ParentId>
<ParentName>Parent 1</ParentName>
</Category>
<Category>
<Id>2</Id>
<Name>Child 1</Name>
<ParentId>1</ParentId>
<ParentName>Parent 1</ParentName>
</Category>
<Category>
<Id>3</Id>
<Name>Child 2</Name>
<ParentId>1</ParentId>
<ParentName>Parent 1</ParentName>
</Category>
<Category>
<Id>8</Id>
<Name>Grand Child 1 -1</Name>
<ParentId>2</ParentId>
<ParentName>Child 1</ParentName>
</Category>
<Category>
<Id>12</Id>
<Name>Parent 2</Name>
<ParentId>12</ParentId>
<ParentName>Parent 2</ParentName>
</Category>
<Category>
<Id>15</Id>
<Name>Child 2-1</Name>
<ParentId>12</ParentId>
<ParentName>Parent 2</ParentName>
</Category>
</Categories>
</CategoryList>
I want to read this xml file (I know how to read it) But I can not format it like follows… How would I get all the nodes that are the top most parents and get child of those parent nodes (using recursion or what so ever)
<ul>
<li>Parent 1
<ul>
<li> Child 1
<ul>
<li>Grand Child 1 -1</li>
</ul>
</li>
<li> Child 2</li>
</ul>
</li>
<li>Parent 2
<ul>
<li>Child 2-1 </li>
</ul>
</li>
</ul>
Please any help will be greatly appreciated….
Edit* What I have done so far…
$xml= simplexml_load_string('myxmlstring');
get_categories($xml, 0);
function get_categories($xml, $id) {
if ($id==0)
$Categories = $xml->xpath('Categories/Category[ParentId=Id]');
else
$Categories = $xml->xpath('Categories/Category[ParentId='.$id.' and Id!='.$id.']');
echo '<ul id="catlist'.$id.'">';
foreach($Categories as $Category) {
echo "<li>ID: " . $Category->Id . "--Name: " . $Category->Name;
get_categories($xml, $Category->Id);
echo "</li>";
}
echo "</ul>";
}
Now I just want to confirm that this is the optimal solution. or someone can come with better idea…
ParentName is excessive, it’s enough to put just parent id.
Since you do a search for each node, execution time will be O(N2), where N is amout of nodes.
There’s an option to do this in linear time, though: Firstly traverse data and build tree structure (or somewhat) and then traverse that structure and output nodes according to it.
Output buffering is also a good option here.
Code may not work or even compile, but you get the idea.