0

Using PHP I make a call to an API. I use curl for this and the response should be XML. But the response of my call is a string which contains the XML content. So I wanted to parse it using simplexml_load_string. But then, I get an empty object:

object(SimpleXMLElement)#839 (0) { }

This is my call:

$curl = curl_init($this->api_base . $this->endpoint);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt($curl, CURLOPT_USERPWD, $this->get_auth_string());
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Content-Type: application/xml',
    'Accept: application/xml',
    'Connection: Keep-Alive'
]);
$response = curl_exec($curl);
$curl_error = curl_error($curl);
curl_close($curl);

What is wrong with that? How can I get a real XML to loop through?

FZC3
  • 1
  • 5
  • check this out: https://stackoverflow.com/questions/561816/php-curl-extract-an-xml-response – lovelace Jun 26 '18 at 08:47
  • That looks like the output you'd get if you ran `simplexml_load_string` over a single empty XML element (e.g. ****) - if your Curl call wasn't returning XML at all, you'd get false instead of an object. Is the value in `$response` definitely what you're expecting? Importantly, using in-built debugging tools like `var_dump` is a bad idea, as they don't give you a full representation of the object. You could also be seeing this if your document was namespaced, see https://stackoverflow.com/questions/44894426/reference-how-do-i-handle-namespaces-tags-and-attributes-with-colon-in-in-si – iainn Jun 26 '18 at 08:55
  • @iainn yes, the response (string) is exactly what I expect and a correct complete XML document – FZC3 Jun 26 '18 at 09:13
  • @lovelace: This code is similar to mine I think... but mine doesnt work – FZC3 Jun 26 '18 at 09:16
  • @FZC3 It sounds like it's namespaced then. `var_dump` won't display namespaced child elements and attributes of an XML document, but it doesn't mean they aren't there (see https://eval.in/1028340). You need to use SimpleXML's internal functionality to parse it - the link to the other question I posted above has a lot more details. – iainn Jun 26 '18 at 09:17
  • @iainn response: `2201...` ----- I need to loop **** – FZC3 Jun 26 '18 at 09:24
  • @iainn I tried using the namespaces like in your example, but the loop does not output anything... – FZC3 Jun 26 '18 at 09:44

0 Answers0