简体   繁体   中英

Can't get data from XML with namespaces

I make a soap request and I get the following response:

<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>
         ...

I have tried to get the element ID inside of <ns1:Event> , but the code bellow doesn't work and don't know why. I searched and tried a fews solutions but without success.

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'));
  }

Use SimpleXMLElement::registerXPathNamespace to register the namespace. For example:

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

and, later:

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

why don't you try this?

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM