I'm having trouble grabbing and iterating through some XML data that is a bit buried. I can get the object to print_r
but not just single attribute value.
Here is the simplified XML. Nests are accurate.
SimpleXMLElement Object (
[@attributes] => Array (
[amenity] => Array (
[0] => SimpleXMLElement Object (
[@attributes] => Array (
[distance] => Within Facility
[name] => Biking
)
)
[1] => SimpleXMLElement Object (
[@attributes] => Array (
[distance] => Within Facility
[name] => Bird Watching
)
)
...
)
)
)
I would like to grab/echo the name of each amenity.
$amenitiesSet = $xml->amenity;
foreach ($amenitiesSet as $am) {
print_r($am[0]);
}
Grabs each object. Every attempt to go deeper is failing. I know it is something simple that I am missing. I am not sure when to use [i]
, ['string']
, ->
etc. I am new to working with XML datasets.
Something like $am[0]->name
?
OK so I finally figured out a solution. The trick with this was to loop over the objects in the object array then change the object attribute to a string. Then I could build the list. Here is the final loop code.
foreach($xml->amenity as $AMN){
$amNameItem = (string)$AMN['name'];
$amList .= $amNameItem.', ';
}
No idea if this is the best solution, but at least I can get my list of object attributes from an array of objects in an array of xml objects.