无法从具有命名空间的 XML 获取数据


Can't get data from XML with namespaces

我发出肥皂请求,得到以下响应:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://*************/******/****" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://*************/******/****/***">
  <SOAP-ENV:Body>
    <ns1:GetEventV2Response>
      <ns1:GetEventV2Result>
       <ns1:Events>
         <ns1:Event>
           <ns1:Id>147624</ns1:Id>
           <ns1:Name>Rockstars</ns1:Name>
         <ns1:Genre>
         ...

我试图在<ns1:Event>中获取元素 ID,但下面的代码不起作用,也不知道为什么。我搜索并尝试了一些解决方案,但没有成功。

header("Content-type: text/xml");
  ....
  $response = curl_exec($ch);
  curl_close($ch);
  x = new SimpleXmlElement($response);
  foreach($x->xpath('//ns1:Event') as $event) {
      var_export($event->xpath('ns1:Id'));
  }

你为什么不试试这个呢?

$xml = simplexml_load_string($xml);
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
foreach ($xml->xpath('//ns1:Event') as $item)
{
    print_r($item);
}

http://php.net/manual/en/function.simplexml-load-string.php

使用 SimpleXMLElement::registerXPathNamespace 注册命名空间。 例如:

$x->registerXPathNamespace('ns1', 'http://*************/******/****');

后来:

$event->registerXPathNamespace('ns1', 'http://*************/******/****');