I have an object returned from $xml = simplexml_load_file($file). I’m trying to access ‘location-id’ and ‘item-id’, but I can’t figure out how to access those pieces of info. If it only nested once, I know I could do something like $xml->{‘item-id’} but it doesn’t seem to work. What is the syntax for this? Sorry for the lack of formatting.. that’s how it was returned on my browser.
SimpleXMLElement Object (
[item] => Array (
[0] => SimpleXMLElement Object (
[@attributes] => Array (
[item-id] => AAA )
[locations] => SimpleXMLElement Object (
[location] => SimpleXMLElement Object (
[@attributes] => Array (
[location-id] => 111
)
[quantity] => 1
[pick-up-now-eligible] => false
)
)
)
[1] => SimpleXMLElement Object
[@attributes] => Array (
[item-id] => BBB
)
[locations] => SimpleXMLElement Object (
[location] => SimpleXMLElement Object (
[@attributes] => Array (
[location-id] => 111
)
[quantity] => 1
[pick-up-now-eligible] => false
)
)
)
)
)
Could somebody chime in? TIA!!
To access attributes in SimpleXML, array-style syntax can be used.
The
SimpleXMLElement::attributes()method is also available. The above would be:If the attribute is namespaced (e.g.
blah:attribute_name) then you can provide that namespace (as the prefix, or URI) to theattributes()method.See the SimpleXML Basic Usage manual page for further information.
To put the above into practice for this individual question, to print the
item-idattribute of the second<item>element, you could use:The example below loops over the
<item>elements and prints their associateditem-idand (the first)location-idvalues.