我正在尝试使用SimpleXML检索处理数据,但遇到了很大的困难。 我在这里阅读了许多关于这个主题的帖子,它们看起来都像我在做什么,但我的不起作用。 这是我得到的:
<ROOT>
<ROWS COMP_ID="165462">
<ROWS COMP_ID="165463">
</ROOT>
我的代码:
$xml = simplexml_load_file('10.xml');
foreach( $xml->ROWS as $comp_row ) {
$id = $comp_row->COMP_ID;
}
当我在调试器中逐步完成此操作时,我可以看到$id没有设置为COMP_ID的字符串值,而是成为包含 CLASSNAME 对象的 SimpleXMLElement 本身。 我已经尝试了许多解决此属性的变体,但没有一种有效,包括 $comp_row->attributes((->COMP_ID 等。
我错过了什么?
SimpleXML 是一个类似数组的对象。备忘单:
- 作为数字索引或可遍历的无前缀子元素
- 不包括前缀元素(注意,我的意思是前缀,而不是空命名空间!
SimpleXMLElement
命名空间的处理很奇怪,可以说是破碎的。 - 第一个孩子:
$sxe[0]
- 具有匹配元素子集的新
SimpleXMLElement
:$sxe->ROWS
、$sxe->{'ROWS'}
- 迭代子项:
foreach ($sxe as $e)
、$sxe->children()
- 文字内容:
(string) $sxe
。SimpleXMLElement
总是返回另一个SimpleXMLElement
,所以如果你需要一个字符串,显式地转换它!
- 不包括前缀元素(注意,我的意思是前缀,而不是空命名空间!
-
带前缀的子元素:
-
$sxe->children('http://example.org')
返回包含元素的新SimpleXMLElement
在匹配的命名空间中,去除命名空间,以便您可以像上一部分一样使用它。
-
-
空命名空间中的属性作为键索引:
- 特定属性:"$sxe["属性名称"]
- 所有属性:
$sxe->attributes()
-
$sxe->attributes()
返回一个特殊SimpleXMLElement
,该将属性显示为子元素和属性,因此以下两者都有效: -
$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']
- 所有属性:
你想要的是:
$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'];
}
你失踪了...
foreach( $xml->ROWS as $comp_row ) {
foreach ($comp_row->attributes() as $attKey => $attValue) {
// i.e., on first iteration: $attKey = 'COMP_ID', $attValue = '165462'
}
}
PHP 手册:SimpleXMLElement::attributes