使用simplexml_load_string获取XML属性

3
可能重复:

可能重复:
从SimpleXML访问@属性

我正在使用一些第三方API,它们通过以下形式的XML返回错误:

<xml>
<status>0</status>
<error code="111">Error message text goes here.</error>
</xml>

使用 PHP 中的 simplexml_load_string 函数,我可以轻松地获取状态 0 和错误消息文本,但是我找不到一种检索 中的 code="111" 值的方法。它似乎被 SimpleXML 忽略了。
<?php
    $bytesRead = file_get_contents('http://api.....');
    $xml = simplexml_load_string($bytesRead);

    echo '<pre>'; print_r($xml); echo '</pre>';
?>

输出
SimpleXMLElement Object
(
    [status] => 0
    [error] => Error message text goes here.
)

我有遗漏什么吗?有没有一种方法可以获得这个值,或者有没有人建议另一种获取它的方法?
2个回答

11

它存在,但在print_r输出中并没有显示。就像基本示例页面的Example #5 Using attributes中所描述的那样:

到目前为止,我们只涵盖了读取元素名称和其值的工作。SimpleXML也可以访问元素属性。访问元素的属性就像访问数组的元素一样。

示例:

$x = '<xml>
<status>0</status>
<error code="111">Error message text goes here.</error>
</xml>';

$attributeObject = simplexml_load_string($x)->error['code'];

print_r($attributeObject);
print_r((string) $attributeObject);

程序输出 (演示)

SimpleXMLElement Object
(
    [0] => 111
)
111

拯救了生命! - Bhavin Rana
在处理[@attributes]时,请使用$obj->attributes()->status - Bhavin Rana

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接