从具有 PHP 中命名空间的 XML 内容中检索值数组

Retrieving an array of values from an XML content with a namespace in PHP

我在检索具有命名空间的 XML 供稿的标签值时遇到一些问题。

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

这样的警告
Warning: SimpleXMLElement::xpath() [simplexmlelement.xpath]: Undefined namespace prefix

我读了Parse XML with Namespace using SimpleXML

XML 供稿数据如下所示:

<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 个标签的值:

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