在PHP中使用SimpleXML获取XML中的父元素?

3

使用$element->children()无法获取当前元素的所有子元素。

但是,如何使用SimpleXML获取当前元素的所有父元素呢?

假设它看起来像这样:

<entity id=1>
   <name>apple</name>
   <entities>
      <entity id=2>
         <name>mac</name>
         <entities>
            <entity id=3>
               <name>safari</name>
            </entity>
         </entities>
      </entity>
   </entities>
</entity>

如果我的当前$elementid=3,我想获取Mac和苹果实体的ID。

使用SimpleXML是否可以实现这一点?因为我找不到任何允许我这样做的函数?


1
重复的https://dev59.com/PnI95IYBdhLWcg3wvwoQ - James Goodwin
1个回答

5
 $element->xpath("ancestor::entity/@id")

1
你能为我解释一下"ancestor::entity/@id"是什么意思吗? - never_had_a_name
它选择所有祖先<entry>节点的id属性。学习XPath,它真的不难。 ;) - Tomalak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接