How can I get values in array from simpleXML object?

Hi,

Got a simplexml object as follows:

    [Attributes] => SimpleXMLElement Object
        (
            [key1] => value1
            [key2] => value1
            [key3] => value1

            [list1] => Array
                (
                    [0] => Some info in here
                    [1] => More info in here
                    [2] => Extra info in here
                    [3] => and so on
                )
            [key4] => value4
        )

what’s the easiest way to get all the values fro the Array called list1?

Thanks

Assuming your print_r output above belongs to something like $xml, then you can loop over the list1 values like:


foreach ($xml->Attributes->list1 as $item) {
    echo $item . PHP_EOL;
}

If you just want to get an array of them, you can construct the array manually in a loop like above or maybe use some fancy tricks (like XPath and array_map) to get an array of the values.

Thanks Salathe,

That worked perfectly!

You can use xpath to get everything in array in a few lines only.

$xml = new SimpleXMLElement($string);
$result = $xml->xpath(‘/Attributes/list1’);
print_r($result);