Search code examples
phpsimplexml

How to adjusts the result pointer of a simpleXML object?


After looping through an entire XML object using foreach loop:

foreach($xml->children() as $xml) {
    echo $xml->title...
}

I need to loop through it again starting from the top.

Having no better way, currently I unset the object and get the XML object again.

I am looking for the right way to do it, perhaps similar to using $result->data_seek(0) for mysqli query results or reset($array) for an array.


Solution

  • The only thing that is stopping you being able to loop over the data again is the way you are using

    foreach($xml->children() as $xml) {
    

    you are overwriting the original document by using as $xml. So if you change the name of that field (using $child in this example) you can just loop over it again...

    foreach($xml->children() as $child) {
        echo $child->asXML().PHP_EOL;
    }
    foreach($xml->children() as $child) {
        echo $child->asXML().PHP_EOL;
    }