我正在尝试处理使用 SimpleXML 检索的数据,但遇到了很大的困难。我在这里阅读了很多关于这个主题的帖子,它们看起来都像我正在做的事情,但我的不起作用。这是我所得到的:
<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;
}
当我在调试器中单步执行此操作时,我可以看到 $id 没有设置为 COMP_ID 的字符串值,而是变成了包含 CLASSNAME 对象的 SimpleXMLElement 本身。我尝试了许多解决此属性的变体,但都不起作用,包括 $comp_row->attributes()->COMP_ID 等。
我缺少什么?
SimpleXML 是一个类似数组的对象。备忘单:
-
Unprefixed child elements as numeric-index or traversable
- 不包括前缀元素(NOTE,我真的是说prefixed, not 空命名空间!
SimpleXMLElement
命名空间的处理很奇怪,而且可以说是损坏的。)
- 第一个孩子:
$sxe[0]
- new
SimpleXMLElement
具有匹配元素的子集:$sxe->ROWS
, $sxe->{'ROWS'}
- 迭代子项:
foreach ($sxe as $e)
, $sxe->children()
- 文字内容:
(string) $sxe
. SimpleXMLElement
总是返回另一个SimpleXMLElement
,所以如果你需要一个字符串明确地投射它!
-
Prefixed child elements:
-
$sxe->children('http://example.org')
返回一个新的SimpleXMLElement
有元素
在匹配的命名空间中,命名空间被剥离所以你可以像上一节一样使用它。
-
Attributes in null namespace as key-index:
- 特定属性:`$sxe['属性名称']
- 所有属性:
$sxe->attributes()
-
$sxe->attributes()
返回一个特殊的SimpleXMLElement
显示属性为both子元素and属性,因此以下两项都有效:
$sxe->attributes()->COMP_ID
$a = $sxe->attributes(); $a['COMP_ID'];
- 属性值:强制转换为字符串
(string) $sxe['attr-name']
-
Attributes in other namespaces:
- 所有属性:
$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'];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)