A possible solution would be to write a recursive function that:
- Main category of current depth
- enter the name of the current category
- If it has child categories, name yourself above them.
The advantage of this solution is that you can keep track of the current depth you are in in your XML document - it can be useful if you need to present your data as a tree, for example.
For example, if you loaded your XML as follows:
$string = <<<XML <catalog> <category name="Category - level 1"> <category name="Category - level 2"> <category name="Category - level 3" /> </category> <category name="Category - level 2"> <category name="Category - level 3" /> </category> </category> </catalog> XML; $xml = simplexml_load_string($string);
You can call the recursive function as follows:
recurse_category($xml);
And this function can be written as follows:
function recurse_category($categories, $depth = 0) { foreach ($categories as $category) { echo str_repeat(' ', 2*$depth); echo (string)$category['name']; echo '<br />'; if ($category->category) { recurse_category($category->category, $depth + 1); } } }
Finally, running this code will give you this output:
Category - level 1 Category - level 2 Category - level 3 Category - level 2 Category - level 3
source share