0

我知道这个问题的答案非常简单,但这是我似乎无法使用 google/SO 解决的问题之一,因为它处理的字符很难搜索。我正在使用 php 从 rest api 获取 xml。我使用了 simple_xml_load_string($string) 现在当我 print_r 我得到这个:

SimpleXMLElement Object
(
    [Seaports] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [Id] => 8675309
                            [Name] => CHORIZON WIRELUSS
                        )                                           
                    [Statistics] => SimpleXMLElement Object
                        (
                            [Clicks] => 194

                        )

ETC

假设我想要

$xml->Seaports[0]->@attributes['Id']

echo $xml->Seaports[0]->@attributes['Id']; 

给我一个语法错误和

echo $xml->Seaports[0]->attributes['Id'];

我究竟做错了什么?

4

1 回答 1

1

这是一个 SimpleXMLElement 对象。“@attributes”行是来自 XML 元素的属性的内部表示。使用 SimpleXML 的函数从该对象获取数据,而不是直接与其交互。或者,一种 hacky 方法是将它转换为这样的数组:

$atts_object = $node->attributes(); //- get all attributes, this is not a real array
$atts_array = (array) $atts_object; //- typecast to an array

 //- grab the value of '@attributes' key, which contains the array your after
 $atts_array = $atts_array['@attributes'];

 var_dump($atts_array);
于 2013-04-30T22:45:21.423 回答