php - XML 命名空间 - 如何获取它们?

标签 php xml xpath

一直在尝试提取一些带有 namespace 的 XML。我自己也尝试去理解这一点;但我似乎无法准确地确定我正在做的事情出了什么问题。

我将其设置为变量$myXMLData,并运行以下代码来吐出标题属性:

$myXMLData=<<<XML
<getmatchingproductresponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
  <getmatchingproductresult asin="055726328X" status="Success">
    <product>
       <attributesets>
        <ns2:itemattributes xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd" xml:lang="en-US">
          <ns2:studio>lulu.com</ns2:studio>
          <ns2:title>You Are a Spiritual Healer</ns2:title>
        </ns2:itemattributes>
      </attributesets>
      <relationships>
      </relationships>
   </product>
  </getmatchingproductresult>
  <responsemetadata>
    <requestid>4304bf06-acd2-4792-804a-394a2e01656f</requestid>
  </responsemetadata>
</getmatchingproductresponse>

XML;

$sxe=new SimpleXMLElement($myXMLData);
$sxe->registerXPathNamespace('ns','http://mws.amazonservices.com/schema/Products/2011-10-01');
$result=$sxe->xpath('//ns:title');
foreach ($result as $title)
  {
  echo $title . "<br>";
  }

但是我的输出是空白的。我在这里做错了什么?请帮忙...!

最佳答案

您确实在 nopaste 中注册了错误的命名空间。这是文档中的两个命名空间。

  • http://mws.amazonservices.com/schema/Products/2011-10-01
    没有前缀的元素
  • http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd
    带有前缀 ns2 的元素

标题使用前缀ns2。您不必注册文档中使用的前缀。您可以而且应该只注册您自己的。在 SimpleXML 中,您必须对任何您想要调用方法 xpath() 的元素执行此操作。它有助于为其创建一个小功能。

$xmlns = [
  'p' => 'http://mws.amazonservices.com/schema/Products/2011-10-01',
  'pd' => 'http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd'
];

function registerNamespacesOnElement(
  SimpleXMLElement $element, array $namespaces
) {
  foreach ($namespaces as $prefix => $namespace) {
    $element->registerXpathNamespace($prefix, $namespace);
  }
}

$sxe=new SimpleXMLElement($xml);
registerNamespacesOnElement($sxe, $xmlns);
$result=$sxe->xpath('//pd:title');
foreach ($result as $title) {
  echo $title . "<br>\n";
}

输出:

You Are a Spiritual Healer<br>

关于php - XML 命名空间 - 如何获取它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38680748/

相关文章:

php - 具有更新计费周期的 Paypal 定期付款

php - 每周一早上 7 点设置一个 cronjob

java - Android/Java - 如何将 HTML 代码附加到我的线性布局?

xml - 如何将一个 XSD 的 XML 转换为另一种非常相似但具有不同 XSD 文件的 XML 格式?

xml - 在 HTTP 中,提示保存和 XML 文件而不是呈现

xml - '仅限字符'检查xsl字符串?

php - 图像在 Bootstrap 行中被拉伸(stretch)

php - 使用 JavaScript 和 PHP 对信用卡进行编码

css - NoSuchElementException 使用 RSelenium 抓取 ESPN

javascript - 我可以使用 XPath 按 CSS 属性过滤元素吗?