2013-01-16 199 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' –