0

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'));
  }
kjhughes
  • 106,133
  • 27
  • 181
  • 240
seal
  • 520
  • 2
  • 5
  • 20

2 Answers2

1

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

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

and, later:

$event->registerXPathNamespace('ns1', 'http://*************/******/****');
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • I follow your suggestion but still doesn't work, I receive the following error: `this page contains the following erros: error on line 1 at column 1: Document is empty. Below is a rendering of the page up to the first error.` :/ – seal Dec 01 '14 at 18:12
  • Did you register the namespace for both `$x` and `$event`? – kjhughes Dec 01 '14 at 18:17
  • yes inside the loop for I put this: `$event->registerXPathNamespace('Event', 'http://*************/******/****');` only if I'm doing wrong – seal Dec 01 '14 at 18:21
  • The first argument to `registerXPathNamespace()` should be the namespace prefix, `'ns1'`. – kjhughes Dec 01 '14 at 18:33
  • I make an `echo $x` and don´t print anything, which is strange because the variable `$response` have the content of result :/ – seal Dec 01 '14 at 19:01
1

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

unixmiah
  • 3,081
  • 1
  • 12
  • 26
  • Also not work. I have a doubt: It's normal in my php file print a string in variable `$response` if I don't set header to `header("Content-type: text/xml");`? – seal Dec 01 '14 at 19:18
  • take a look at this post: http://stackoverflow.com/questions/2773497/soap-response-to-xml-with-simplexml – unixmiah Dec 01 '14 at 20:19