SimpleXmlElement和XPath,获取空数组()

jax*_*jax 10 php xpath simplexml xml-namespaces

我从谷歌结帐响应中解析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');
Run Code Online (Sandbox Code Playgroud)

一个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>
Run Code Online (Sandbox Code Playgroud)

Gor*_*don 18

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

例:

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

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

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

在将XML提供给SimpleXmlElement之前.

  • +1好的解释和实际的例子.伙计们,请花点时间了解名称空间.它们并不那么难,从长远来看理解它们要比不断试图躲避它们更容易. (5认同)