This seems like it would be a rather simple task.

XML given:

<items>
<item attr="1"/>
<item attr="2"/>
<item attr="3"/>
</items>

So typically:

$doc = new DOMdocument();
$doc->load($xml);

$xpath = new DOMXpath($doc);

$items = $xpath->query('/items/item');

foreach ($item as $item)
{
echo $item->getAttribute('attr');
}

So that would return: 123

So my question is, how would you query the document from the bottom such that results would be: 321

I did try using a for loop:

$numItems = $items->length;

for($i=$numItems;$i>0;$i--)
{
echo $items->item($i)->getAttribute('attr');
}

But I get an error on trying to access the attribute.

I'm sure there's a way to either:

1) modify the query to look from the bottom

2) use the for loop properly

3) last resort, actually reverse the nodeList but at the cost of further processing overheard

Any ideas would be greatly appreciated

    You could store it in an array, and use [man]array_reverse[man] like so:

    $newitems = array();
    foreach( $items as $item ) {
       $newitems[] = $item->getAttribute('attr');
    }
    $newitems = array_reverse($newitems);
    

    Also I think the $i should be on the $items and also in brackets not parenthesis, I would think this would be causing a parse error anyway as item is not a method of $items...

      The [font=monospace]for[/font] loop is suffering from an off-by-one error: the last item is [font=monospace]$numItems-1[/font], and the loop should stop when it reaches 0, not immediately before.

        @weed: that did it

        I'd REALLY like to know if its possible to do the lookup in reverse though via XPATH... I've read a bunch about fn:reverse and reverse axis but no where can I find a working example of reverse document XPATH'ing

          Reverse axes are those that work back through the document from the current node towards the root; ancestor, ancestor-or-self, preceding-sibling, and preceding.

          /items/item[last()] | /items/item[last()]/preceding-sibling::item

          Probably not worth it 🙂

          fn:reverse is XPath 2; for some reason DOMXPath still only supports XPath 1.

            Weedpacket;11006909 wrote:

            fn:reverse is XPath 2; for some reason DOMXPath still only supports XPath 1.

            Cmon PHP catch up!

            I'll give your suggestions a try... I had played with them but couldn't get em' working.

            I presume using last() and sibling will just add processing overhead to crawl the DOM forward to then walk it backwards

            What I may simply do is alter my SQL query that generates the XML feed to use a 'desc' order. Since I'm the only one using the data it won't affect anyone negatively.

              Write a Reply...