Reorder a nested HTML list in PHP

Recently I was working on website where I had to re-order a nested list (part of a navigation menu) – unfortunately I only had access to fragment of HTML so I couldn’t just manipulate the arrays from which it was built. The menu was compiled from various arrays and months within years sometimes came out all wrong.

So I thought, I’d just treat it as a bit of XML (which obviously it is) and re-order it using PHPs native XML handling classes. XML is one of those things that I use frequently, but never really do anything with, and finding a solution took me rather longer than I had expected. It is a mixture of simpleXML and XMLDom.

One of the main problems was the lack any real examples.

If anyone can suggest a more elegant solution, I would love to hear it.

Here is my code:

The UL to re-order

As you can see the month names are in the wrong order



My (woeful) solution


$xml = simplexml_load_string($string);
	
// pull a node tree as an Array out using simpleXML xpath
$trees = $xml->xpath('/ul/li/ul');

$array = array();
$order = array();

$i = 0;

// we only need to delve into XML if there are any nested