【问题标题】:Get xml attribute using simplexml_load_string [duplicate]使用 simplexml_load_string 获取 xml 属性 [重复]
【发布时间】:2012-12-30 20:17:44
【问题描述】:

可能重复:
Accessing @attribute from SimpleXML

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

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

在 PHP 中使用 simplexml_load_string 可以轻松获取状态 0 和错误消息文本,但我找不到从 &lt;error code="111"&gt; 检索 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.
)

我错过了什么吗?有没有办法获得这个值,或者有人可以建议另一种方法来获得这个值吗?

【问题讨论】:

    标签: php xml simplexml


    【解决方案1】:

    它在那里,但没有显示在print_r 输出中。赞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
    

    【讨论】:

    • 救了命! .....
    • 如果出现`[@attributes],请使用$obj-&gt;attributes()-&gt;status
    【解决方案2】:

    就这样使用 echo $xml->error['code'];

    例如: http://codepad.org/uOqeBNz9

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-30
      • 2015-03-15
      • 2015-02-18
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      相关资源
      最近更新 更多