PDA

View Full Version : A question about reordering XML



mtimofiiv
27 Apr 2010, 06:31 PM
Hi there, so here's my sample XML file:



<root>
<item number="1"/>
<item number="4"/>
<item number="2"/>
<item number="3"/>
</root>


I'm building a backend to edit some XML for a client out of PHP, and I need it to sort the items by the "number" attribute. I've tried a few methods, including arrays, but I seem to be having some trouble still. I can't use XSLT unfortunately on the server where this is heading.

I've played with the following code so far, but I seem to be having trouble saving it back into the XML file after.



$url = '_db/items.xml';
$file = simplexml_load_file($url);
$sxe = new SimpleXMLElement($file->asXML());

$nodes = $sxe->xpath('/root/item');

function sort_items($t1, $t2) {
return strcmp($t1['number'], $t2['number']);
}

usort($nodes, 'sort_items');
$sxe->asXML($url);

Any ideas?:teleport:

mtimofiiv
28 Apr 2010, 11:36 AM
Oh, and I forgot to mention.


var_dump($nodes);

This returns an array with SimpleXMLElement objects in it. So maybe the problem is that it's in an array?