Samy Massoud
Samy Massoud

Reputation: 4385

read xml file from end to start in php

i want to read xml file from end to start suppose my xml like that :

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<to>Samy</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't Miss me this weekend!</body>
</note>

i need to read last note first i use code like that

$x = $xmldoc->getElementsByTagName('note');
        $nofnews = $xmldoc->getElementsByTagName('note')->length;
        for ($i = 0; $i < $nofnews; $i++) {
            $item_title = $x->item($i)->getElementsByTagName('to')
                            ->item(0)->nodeValue;
            $item_link = $x->item($i)->getElementsByTagName('from')
                            ->item(0)->nodeValue;
                            }

thank you in advance

Upvotes: 3

Views: 1472

Answers (2)

hakre
hakre

Reputation: 197832

getElementsByTagName returns a DOMNodeList. You can access each element by it's numerical index (0 to length-1) as you already do, but just start at the end, not the beginning in your for loop, then count downwards:

$x = $xmldoc->getElementsByTagName('note');
$nofnews = $x->length;
for ($i = $nofnews-1; $i > -1; $i--)
{
    $item = $x->item($i);
    $item_title = $item->getElementsByTagName('to')
                        ->item(0)->nodeValue;
    $item_link = $item->getElementsByTagName('from')
                        ->item(0)->nodeValue;
}

This should already to it for you.

Upvotes: 1

user400055
user400055

Reputation:

I am not sure that I understand your question correctly but it seems you want to start reading the XML document's root element's children in reverse order?

(Also the example content you're giving is taken from here: http://www.w3schools.com/PHP/php_xml_simplexml.asp) why not follow their example?

But anyway, this should do the trick:

<?php
$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "<br />";

foreach(array_reverse($xml->children()) as $child)
  {
  // process your child element in here
  }
?>

--> make use of the array_reverse() function: http://www.w3schools.com/php/func_array_reverse.asp

Upvotes: 0

Related Questions