【问题标题】:PHP XML get children variables from parent using namespacesPHP XML使用命名空间从父级获取子变量
【发布时间】:2018-07-22 09:42:40
【问题描述】:

我如何从下面的 xml 标记中获取 a b c d e...

<api:field name="test">
    <api:text>a</api:text>
    <api:text>b</api:text>
    <api:text>c</api:text>
    <api:text>d</api:text>
    <api:text>e</api:text>
</api:field>

我正在尝试使用这个 for 循环:

foreach ($xml->xpath('//api:field[@name="test"]') as $item)
{
    foreach ($item->children() as $child) {
        ...
    }
}

但我不知道如何访问不包含属性的子节点。

我需要专门获取父节点“test”的子值,所以请不要给我 $xml->xpath("//api:text"); 作为答案.这个答案的问题是我们可能会在其他父节点下看到 ,而我只想从特定的父节点获取子值。在这种情况下 name="test"

【问题讨论】:

    标签: php xml namespaces


    【解决方案1】:

    有几种方法可以实现这一目标。要么只是扩展您的 xpath 表达式以返回子节点本身:

    foreach ($sxml->xpath('/api:field[@name="test"]/api:text') as $item) {
        echo (string) $item, PHP_EOL;
    }
    

    或者,如果您确实想使用两个循环(或者它更适合您的用例),您只需将命名空间前缀传递给 children() 方法:

    foreach ($sxml->xpath('/api:field[@name="test"]') as $item) {
        foreach ($item->children('api', true) as $child) {
            echo (string) $child, PHP_EOL;
        }
    }
    

    (如果命名空间前缀可能发生变化,可以使用registerXPathNamespace方法注册一个持久化的,根据定义的命名空间URL。)

    这两种方法都会产生相同的结果:

    一个
    b
    c
    d
    e

    完整示例请参见https://eval.in/954569

    【讨论】:

    • 感谢您的回答!它有效,但我确实必须在 xpath 中添加一个额外的“/”才能使其工作。再次感谢。
    猜你喜欢
    • 2019-11-16
    • 2017-07-08
    • 1970-01-01
    • 2017-12-18
    • 2017-05-20
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    相关资源
    最近更新 更多