Looping through SimpleXMLElement to access attribu

2019-02-25 23:59发布

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?

2条回答
神经病院院长
2楼-- · 2019-02-26 00:27

You're missing...

foreach( $xml->ROWS as $comp_row ) {
    foreach ($comp_row->attributes() as $attKey => $attValue) {
        // i.e., on first iteration: $attKey = 'COMP_ID', $attValue = '165462'
    }
}

PHP Manual: SimpleXMLElement::attributes

查看更多
迷人小祖宗
3楼-- · 2019-02-26 00:34

SimpleXML is an array-like object. Cheat sheet:

  • Unprefixed child elements as numeric-index or traversable
    • Does not include prefixed elements (NOTE, I really mean prefixed, not null-namespace! SimpleXMLElement handling of namespaces is a strange and arguably broken.)
    • first child: $sxe[0]
    • new SimpleXMLElement with a subset of matching elements: $sxe->ROWS, $sxe->{'ROWS'}
    • iterate children: foreach ($sxe as $e), $sxe->children()
    • Text content: (string) $sxe. SimpleXMLElement always returns another SimpleXMLElement, so if you need a string cast it explicitly!
  • Prefixed child elements:
    • $sxe->children('http://example.org') returns a new SimpleXMLElement with elements in the matching namespace, with namespace stripped so you can use it like the previous section.
  • Attributes in null namespace as key-index:
    • specific attribute: `$sxe['attribute-name']
    • all attributes: $sxe->attributes()
    • $sxe->attributes() returns a special SimpleXMLElement that shows attributes as both child elements and attributes, so both the following work:
    • $sxe->attributes()->COMP_ID
    • $a = $sxe->attributes(); $a['COMP_ID'];
    • Value of an attribute: coerce to string (string) $sxe['attr-name']
  • Attributes in other namespaces:
    • all attributes: $sxe->attributes('http://example.org')
    • specific attribute: $sxe_attrs = $sxe->attributes('http://example.org'); $sxe_attrs['attr-name-without-prefix']

What you want is:

$xml = '<ROOT><ROWS COMP_ID="165462"/><ROWS COMP_ID="165463"/></ROOT>';

$sxe = simplexml_load_string($xml);

foreach($sxe->ROWS as $row) {
    $id = (string) $row['COMP_ID'];
}
查看更多
登录 后发表回答