PHP simplexml读取子标签属性

PHP simplexml reading child tag attribute

我有一个 xml 如下所示,

<y>
 <n>
   <n id='test1'></n>
   <n id='test2'></n>
 </n>
</y>

并想阅读子 "n" 标签的每个 "id"。

我使用这个 php 代码;

$xml = simplexml_load_file("my.xml");
echo $xml->n[0]->n;

但是出现错误,

Trying to get property of non-object

应该是:$xml->n->n[0]这是一个数组。如果您的 print_r($xml) 您可能会看到这样的内容:

SimpleXMLElement Object
(
    [n] => SimpleXMLElement Object
    (
        [n] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [id] => test1
                            )

                    )

                [1] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [id] => test2
                            )

                    )

            )

    )

)