PHP SimpleXML解析同名节点数组时无法获取节点属性问题
如何用PHP SimpleXML获取XML节点的属性?
你的XML结构如下:
<object> <attributes> <attribute id="1" name="first">First Value</attribute> <attribute id="2" name="second">Second Value</attribute> <attribute id="3" name="third">Third Value</attribute> </attributes> </object>
使用print_r()输出SimpleXMLElement对象时,只会默认展示节点的文本内容,不会显示属性,但属性实际上可以通过SimpleXML的API正常获取。
解决方法
方法1:通过attributes()方法获取属性
遍历每个<attribute>节点,调用attributes()方法获取节点的属性集合,再访问具体属性:
<?php $xml = <<<XML <object> <attributes> <attribute id="1" name="first">First Value</attribute> <attribute id="2" name="second">Second Value</attribute> <attribute id="3" name="third">Third Value</attribute> </attributes> </object> XML; $obj = simplexml_load_string($xml); foreach ($obj->attributes->attribute as $attrNode) { // 显式转换为字符串,避免返回SimpleXMLElement对象 $id = (string)$attrNode->attributes()->id; $name = (string)$attrNode->attributes()->name; $value = (string)$attrNode; echo "ID: {$id}, 名称: {$name}, 值: {$value}\n"; }
方法2:直接通过数组下标访问属性
SimpleXML支持直接用数组下标语法访问节点属性,写法更简洁:
<?php $xml = <<<XML <object> <attributes> <attribute id="1" name="first">First Value</attribute> <attribute id="2" name="second">Second Value</attribute> <attribute id="3" name="third">Third Value</attribute> </attributes> </object> XML; $obj = simplexml_load_string($xml); foreach ($obj->attributes->attribute as $attrNode) { $id = (string)$attrNode['id']; $name = (string)$attrNode['name']; $value = (string)$attrNode; echo "ID: {$id}, 名称: {$name}, 值: {$value}\n"; }
关键说明
- 必须把属性或节点内容转换为字符串(
(string)),因为SimpleXML返回的是SimpleXMLElement对象,直接使用可能出现非预期行为。 - 若需调试,
var_dump()会比print_r()显示更多节点细节,但获取属性仍需通过上述两种方式。
内容的提问来源于stack exchange,提问作者T-Regex
相关产品推荐
相关产品推荐

