我正在尝试使用 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 是一个类似数组的对象。备忘单:
- 无前缀子元素作为数字索引或可遍历
- 不包括前缀元素(注意,我的意思是前缀,而不是null-namespace!
SimpleXMLElement
namespace 的处理很奇怪,而且可以说是错误的。) - 第一个 child :
$sxe[0]
- 新
SimpleXMLElement
具有匹配元素的子集:$sxe->ROWS
,$sxe->{'ROWS'}
< - 迭代 child :
foreach ($sxe as $e)
,$sxe->children()
- 文本内容:
(string) $sxe
。SimpleXMLElement
总是返回另一个SimpleXMLElement
,所以如果您需要一个字符串,显式转换它!
- 不包括前缀元素(注意,我的意思是前缀,而不是null-namespace!
- 带前缀的子元素:
$sxe->children('http://example.org')
返回带有元素的新SimpleXMLElement
在匹配的命名空间中,剥离了命名空间,以便您可以像上一节一样使用它。
- null 命名空间中的属性 作为键索引:
- 特定属性:`$sxe['attribute-name']
- 所有属性:
$sxe->attributes()
$sxe->attributes()
返回一个特殊的SimpleXMLElement
,它将属性显示为 both 子元素 and属性,所以以下两个工作:$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'];
}
关于php - 循环遍历 SimpleXMLElement 以访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14420895/