I seem to be getting back a well-formed XML document from this cURL, but I can’t seem to parse this return using the SimpleXMLElement class. This is the iteration of code that I’m working with now:
$url = "http://rosemary.umw.edu/~stephen/cpsc448/numCredits.php?prefix=". $prefix ."&number=" . $number; // prefix=cpsc&number=220
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15);
$resp = curl_exec($ch);
echo $resp;
This returns:
<?xml version="1.0"?><NumCredits>4</NumCredits>
This is how I’m currently trying to parse the return:
$xml = new SimpleXMLElement($resp);
echo $xml->NumCredits[0];
Using this I don’t get a response. I’ve also tried this method without success:
$dom = new DOMDocument;
$dom->loadXML($resp);
if (!$dom) {
echo 'Error parsing document';
exit;
}
$simpleXML = simplexml_import_dom($dom);
echo $simpleXML;
return $simpleXML->NumCredits[0];
I have to be doing something wrong here but I can’t quite figure out why it’s so hard to parse this return.
You only have one element in your XML, so it is considered the document root:
Will output:
Thus it can be accessed as
$xml[0];If you want to be able to access it by the element name, you will need to add a root element to your XML, for example:
Once this document is parsed, you can access the value using
$xml->NumCredits;