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?

7
  • check this out: stackoverflow.com/questions/561816/… Commented Jun 26, 2018 at 8:47
  • That looks like the output you'd get if you ran simplexml_load_string over a single empty XML element (e.g. <foo />) - 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 stackoverflow.com/questions/44894426/… Commented Jun 26, 2018 at 8:55
  • @iainn yes, the response (string) is exactly what I expect and a correct complete XML document Commented Jun 26, 2018 at 9:13
  • @lovelace: This code is similar to mine I think... but mine doesnt work Commented Jun 26, 2018 at 9: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 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. Commented Jun 26, 2018 at 9:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.