编程语言
首页 > 编程语言> > php – SimpleXmlElement和XPath,获取空数组()

php – SimpleXmlElement和XPath,获取空数组()

作者:互联网

我从谷歌结帐响应中解析XML时遇到了一些麻烦. XML直接来自谷歌服务器,所以XML本身没有问题.

我想掌握所有新订单通知标签

我试过这个,但每次都返回一个空数组().

$xml = new SimpleXmlElement($raw_xml);
$notifications = $xml->xpath('notifications');
$notifications = $xml->xpath('/notification-history-response/notifications/new-order-notification');
$notifications = $xml->xpath('//new-order-notification');

一个XML snipet(刚刚开始)

<notification-history-response xmlns="http://checkout.google.com/schema/2" serial-number="c5cda190-0eb1-4f91-87cd-e656e5598d38">
  <notifications>
    <new-order-notification serial-number="271578974677716-00001-7">
      <buyer-billing-address>
        <address1>19 sandbox st</address1>
        <address2></address2>

解决方法:

问题可能是默认命名空间.看到

> SimpleXMLElement::registerXPathNamespace
为下一个XPath查询创建前缀/ ns上下文

例:

$sxe->registerXPathNamespace('x', 'http://checkout.google.com/schema/2');
$result = $sxe->xpath('//x:notifications');

作为替代方案,如果没有其他名称空间,只需删除默认名称空间

str_replace('xmlns="http://checkout.google.com/schema/2"', '', $raw_xml);

在将XML提供给SimpleXmlElement之前.

标签:php,xpath,xml-namespaces,simplexml
来源: https://codeday.me/bug/20190927/1823341.html