could you be so kind to help me solve a problem i have inverse sorting elements of a xml file by their attribute values?
I have this xml file (news2.rss):
Code: Select all
<?xml version="1.0" encoding="iso-8859-1"?>
<Menu>
<myItem id="1" name="Item"/>
<myItem id="4" name="Item"/>
<myItem id="2" name="Item"/>
<myItem id="6" name="Item"/>
<myItem id="9" name="Item"/>
</Menu>
and i would like to order the xml file in decrescent numeric order by id attributes like this:
Code: Select all
<?xml version="1.0" encoding="iso-8859-1"?>
<Menu>
<myItem id="9" name="Item"/>
<myItem id="6" name="Item"/>
<myItem id="4" name="Item"/>
<myItem id="2" name="Item"/>
<myItem id="1" name="Item"/>
</Menu>
I found the solution of strcmp function very interesting but i was not able to put it on the right way to do the job i need.
This is my "not working" php code:
Code: Select all
<?php
// DOM creation (working)
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
// XML loading (working)
$doc->load("news2.rss");
$root = $doc->documentElement;
// get array $news from myItem nodes (Working)
$news= $root->getElementsByTagName('myItem');
//function to reorder the $news array (Not working)
function my_sort($a, $b)
{
$compare1 = strcmp($news->item($a)->getAttributeNode('id')->value, $news->item($b)->getAttributeNode('id')->value);
if ( $compare1 > 0 )
{
return $compare1;
}
}
usort($news, "my_sort");
// Save the update xml file
print $doc->save("news2.rss");
I will be very grateful to you if you could help me in setting up this code.
Thank you in advance
stefano