I am trying process data retrieved with SimpleXML and am having great difficulty. I have read numerous threads here about this subject, they all LOOK like what I am doing, but mine are not working. Here's what I've got:
<ROOT>
<ROWS COMP_ID="165462">
<ROWS COMP_ID="165463">
</ROOT>
My code:
$xml = simplexml_load_file('10.xml');
foreach( $xml->ROWS as $comp_row ) {
$id = $comp_row->COMP_ID;
}
As I step through this in my debugger, I can see that $id is not set to the string value of COMP_ID, but becomes a SimpleXMLElement itself containing the CLASSNAME object. I've tried many variations of addressing this attribute but none work, including $comp_row->attributes()->COMP_ID and others.
What am I missing?
You're missing...
PHP Manual: SimpleXMLElement::attributes
SimpleXML is an array-like object. Cheat sheet:
SimpleXMLElement
handling of namespaces is a strange and arguably broken.)$sxe[0]
SimpleXMLElement
with a subset of matching elements:$sxe->ROWS
,$sxe->{'ROWS'}
foreach ($sxe as $e)
,$sxe->children()
(string) $sxe
.SimpleXMLElement
always returns anotherSimpleXMLElement
, so if you need a string cast it explicitly!$sxe->children('http://example.org')
returns a newSimpleXMLElement
with elements in the matching namespace, with namespace stripped so you can use it like the previous section.$sxe->attributes()
$sxe->attributes()
returns a specialSimpleXMLElement
that shows attributes as both child elements and attributes, so both the following work:$sxe->attributes()->COMP_ID
$a = $sxe->attributes(); $a['COMP_ID'];
(string) $sxe['attr-name']
$sxe->attributes('http://example.org')
$sxe_attrs = $sxe->attributes('http://example.org'); $sxe_attrs['attr-name-without-prefix']
What you want is: