Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP simplexml reverse

Tags:

php

simplexml

Is there any way to loop through an xml loaded in simpleXML in reverse? say if i have the following xml

$string ="<items>
    <item>1</item>
    <item>2</item>
    <item>3</item> 
</items>";

$xml = simplexml_load_string($string);

is there any way to reverse $xml so that i get item 3 when i do a foreach

like image 674
Rupert Avatar asked Dec 05 '22 01:12

Rupert


2 Answers

Assuming the OP is a beginner only interested in a solution I'd recommend using xpath() to get the elements and array_reverse() to reverse their order:

$items = array_reverse($xml->xpath('item'));

Note: the XPath "item" grabs all <item/> elements that are the direct children of current element.

like image 60
Josh Davis Avatar answered Jan 03 '23 19:01

Josh Davis


$items = $xml->item;
for ($i = count($items) - 1; $i >= 0; $i--)
{
    echo (string) $items[$i].", ";
}
like image 42
Sjoerd Avatar answered Jan 03 '23 19:01

Sjoerd