PHP - 获取特定类型的所有 XML 子节点 [英] PHP - get all XML child nodes of a specific type

查看:98
本文介绍了PHP - 获取特定类型的所有 XML 子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的 XML 结构:

I have an XML structure like this:

<root>
    <parent>
        <child name='Child1' />
        <child name='Child2' />
        <subparent>
            <child name='Child3' />
        </subparent>
    </parent>
    <child name='Child4' />
<root>

使用 PHP simplexml 我正在尝试获取所有"节点,无论是什么级别,我想知道是否有快速功能, 而不是扫描 XML 的每个节点.

Using PHP simplexml I am trying o get all the 'child' nodes, no matter what level, and I would like to know if there's a quick function for that, instead of scanning each node of the XML.

推荐答案

当然,您需要做的就是使用 xpath() 查询您的 XML:

Sure, all you need to do is use an xpath() query on your XML:

$xml = simplexml_load_string( $xml);

foreach( $xml->xpath( '//child') as $child) { 
    $attributes = $child->attributes();
    echo $attributes['name'] . "\n";
}

你可以从这个演示看到这个打印:

You can see from this demo that this prints:

Child1 
Child2 
Child3 
Child4

这篇关于PHP - 获取特定类型的所有 XML 子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆