SimpleXML,使用带括号语法的子索引选择节点

问题描述 投票:0回答:2

我正在使用SimpleXML来引入XML提要。我需要获取具有相同名称的第二个节点。

Feed示例是:

<parent-node>
    <child-node>
        <the-node>
            <the-target>Text</target>
        </the-node>
        <the-node>
            <the-target>Text</target>
        </the-node>
    </child-node>
</parent-node>

由于我所针对的节点使用连字符,我需要使用括号语法

$item->{'parent-node'}->{'child-node'}->{'the-node'}这将抓住第一个<the-node>

当使用括号语法时,我无法使用以下任何一个选择第二个<the-node><the-target> ...

$item->{'parent-node'}->{'child-node'}->{'the-node[2]'}->{'the-target'}

$item->{'parent-node'}->{'child-node'}->{'the-node'[2]}->{'the-target'}

$item->{'parent-node'}->{'child-node'}->{'the-node'}[2]->{'the-target'}

我的问题是,如何在使用括号语法获取第二个<the-node><target>时定位childIndex?

- - 更新 - -

在一些答案之后,我尝试了以下但没有运气

$item->{'parent-node'}->{'child-node'}->{'the-node'}[1]->{'the-target'}

$item->{'parent-node'}->{'child-node'}->{'the-node'}->{'the-target'}[1]

$item->{'child-node'}->{'the-node'}->{'the-target'}[1]

php xml simplexml
2个回答
0
投票

SimpleXMLElement存储兄弟节点,就好像它们是一个数组一样。这通常表示值以0为基础的索引存储,即。数组中的第一个值从索引0开始。

因此,在这种情况下,只能使用索引1而不是2访问第二个兄弟节点。

默认情况下也不必遍历根级节点(除非您省略了其他一些XML或使用了一些非默认设置)。

试试这个:

// Will grab the 2nd <the-node/>
$node = $item->{'child-node'}->{'the-node'}[1];

根据您的初始代码是否在没有数组访问权限的情况下工作,您也可以尝试:

// Testing locally I was not able to use this and got an error
// But maybe things are omitted in your question.
$node = $item->{'parent-node'}->{'child-node'}->{'the-node'}[1];

0
投票

正确的语法如下所示:

$item->{'child-node'}->{'the-node'}[0]; // First the-node
$item->{'child-node'}->{'the-node'}[1]; // Second the-node

如果parent-node是所有其他元素的根元素,则无法显式访问它。

$item->{'parent-node'}->{'child-node'}->{'the-node'}[0];

上面的代码将导致错误说“试图获取非对象的属性”。

由于parent-node是顶级根元素,因此无法显式访问它。

只有top根元素的immediate子元素才可以在SimpleXMLElement对象中访问。

© www.soinside.com 2019 - 2024. All rights reserved.