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?
simplexml_load_stringover 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$responsedefinitely what you're expecting? Importantly, using in-built debugging tools likevar_dumpis 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/…var_dumpwon'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.