使用 PHP 中的命名空间从 XML 内容中检索值数组 [英] Retrieving an array of values from an XML content with a namespace in PHP

查看:22
本文介绍了使用 PHP 中的命名空间从 XML 内容中检索值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在检索具有命名空间的 XML 提要的标签值时遇到了一些问题.

I'm having some issues retrieving the tag values of an XML feed which has a namespace.

我已经阅读并尝试实现了之前问题的一些推荐答案,但我仍然得到一个空数组,或者像

I've read and tried to implement some of the recommended answers on previous questions, but I still get an empty array, or a warning like

Warning: SimpleXMLElement::xpath() [simplexmlelement.xpath]: Undefined namespace prefix

我阅读了使用 SimpleXML 使用命名空间解析 XML.

XML 提要数据如下所示:

The XML feed data looks like this:

<Session>
      <AreComplimentariesAllowed>true</AreComplimentariesAllowed>
      <Attributes xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
         <d3p1:string>0000000009</d3p1:string>
         <d3p1:string>0000000011</d3p1:string>
      </Attributes>
</Session>

我当前的代码:

foreach($xml->Session as $event){
    if(!empty($event->Attributes)){
        foreach($event->xpath('//Attributes:d3p1') as $atts) {
             echo $atts."<br />";
        }
    }
}

任何指导将不胜感激.

谢谢.

推荐答案

需要注册命名空间:

foreach ($xml->xpath('//Attributes') as $attr) {
  $attr->registerXPathNamespace('ns',
    'http://schemas.microsoft.com/2003/10/Serialization/Arrays');
  foreach ($attr->xpath('//ns:string') as $string) {
    echo $string, PHP_EOL;
  }
}

如果您只想获取 string 标签的值:

In case if you want to fetch only the values of string tags:

$xml->registerXPathNamespace('ns',
  'http://schemas.microsoft.com/2003/10/Serialization/Arrays');
foreach ($xml->xpath('//Attributes/ns:string') as $string) {
  echo $string, PHP_EOL;
}

这篇关于使用 PHP 中的命名空间从 XML 内容中检索值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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