tags:

views:

52

answers:

1

Hi i have a problems with simplexml_load_file, i'm not pretty sure how to do to order my array by a $item->padre.

I need to do foreach and order by $item->padre.=, i don't know how to do this.

function create_sitemap($sitemap){

 $xml = file_exists('sitemap.xml') ? $xml = simplexml_load_file('sitemap.xml'): exit('Failed to open sitemal.xml.');

 $xml = uasort($xml, function($a,$b){ return strcmp($a->padre, $b->padre); });


 foreach ($xml->url as $item) {

   echo "<p>" . $item->loc. "</p>";
   echo "<p>" . $item->padre . "</p>";

 } 

}

Thanks in advance.

+1  A: 

$xml is not an array but a SimpleXMLElement and therefore usort() won't work this way.
But e.g. SimpleXMLElement->xpath() returns an array and you can use it to find all <url> elements.

create_sitemap('test');

function create_sitemap($sitemap){
  $xml = getData();
  $urls = $xml->xpath('url');

  uasort($urls, function($a,$b){ return strcmp($a->padre, $b->padre); });

  foreach ($urls as $item) {
    echo "<p>{$item->loc}</p><p>{$item->padre}</p>\n";
  } 
}

function getData() {
  return new SimpleXMLElement('<xml>
    <url>
      <loc>loc Z</loc>
      <padre>padre Z</padre>
    </url>
    <url>
      <loc>loc A</loc>
      <padre>padre A</padre>
    </url>
    <url>
      <loc>loc C</loc>
      <padre>padre C</padre>
    </url>
    <url>
      <loc>loc B</loc>
      <padre>padre B</padre>
    </url>
  </xml>');
}

prints

<p>loc A</p><p>padre A</p>
<p>loc B</p><p>padre B</p>
<p>loc C</p><p>padre C</p>
<p>loc Z</p><p>padre Z</p>

You might also be interested in xslt

VolkerK