2013-01-16 205 views
3

可能重复:
Accessing @attribute from SimpleXML获取XML属性

我使用的是一些第三方的API,其通过XML返回以下形式的错误:

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

在PHP中使用simplexml_load_string我可以很容易地得到状态0和错误消息文本,但我找不到从<error code="111">检索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. 
) 

我缺少的东西?有没有办法获得这个价值,或有人建议另一种方法来获得这个?

回答

12

它在那里,但只是不显示在print_r输出。 Like the basic examples page coins it in Example #5 Using attributes

到目前为止,我们只介绍了读取元素名称及其值的工作。 SimpleXML也可以访问元素属性。像元素array一样访问元素的属性。

实施例:

$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); 

程序输出(Demo

SimpleXMLElement Object 
(
    [0] => 111 
) 
111 
+0

这么简单,谢谢! –

+0

拯救了生命! .............. –

+0

['@attributes]'使用'$ obj-> attributes() - > status' –