Page 1 of 1

Sorting an xml file by its elements attribute via php

Posted: Thu Nov 13, 2008 4:54 am
by moodup.it
Hi all,
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

Re: Sorting an xml file by its elements attribute via php

Posted: Thu Nov 13, 2008 12:46 pm
by josh
Are you trying to parse the XML sort it and re-write it back, or sort it based on the text? What's the issue?

Re: Sorting an xml file by its elements attribute via php

Posted: Thu Nov 13, 2008 4:02 pm
by moodup.it
Actually i made this code

Code: Select all

<?php 
 
$doc = new DOMDocument(); 
$doc->preserveWhiteSpace = false; 
 
 
$doc->load("news.rss"); 
$root = $doc->documentElement; 
 
 
$news= $root->getElementsByTagName('myItem'); 
 
 
function my_sort($a, $b)  
{  
return strcmp($a->getAttributeNode('id')->value, $b->getAttributeNode('id')->value);  
}  
usort($news, "my_sort");  
 
 
 
 
 
foreach ($news as $new) 
{$root->appendChild($new); 
 }  
 
print $doc->save("news.rss"); 
 
 
?>

What i want is to write back the same xml with elements ordered by id in descendent order (from the higher to the lower).
Thanks for replying
Stefano