Looping through SimpleXMLElement to access attributes

感情迁移 提交于 2019-12-01 21:41:27

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'];
}

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!