Error handing with curl

So I’m using this code:

$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, $feedurl);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

ob_start();
curl_exec($ch);
curl_close($ch);
$feed = ob_get_contents();
ob_end_clean();

$xmlData = new SimpleXMLElement($feed);

…and I sometimes get the error

Fatal error: Uncaught exception ‘Exception’ with message ‘String could not be parsed as XML’ in … on line 41

Is there some way to had some error handling to it? …or something?

Cheers :slight_smile:

I think your error is coming from the SimpleXMLElement rather than curl.

Is your XML valid? Try echoing your response so you know what simplexml is trying to parse.

The exception is being thrown by SimpleXML because the data you’re passing it is not valid XML.


$curl = curl_init('http://www.example.org/feed.rss');
curl_setopt_array(
    $curl,
    array(
        CURLOPT_CONNECTTIMEOUT  => 5,
        CURLOPT_RETURNTRANSFER  => true
    )
);

if(false !== ($data = curl_exec($curl))){
    try{
        $xml = new SimpleXMLElement($data);
    }catch(Exception $exception){
        $xml = false;
    }
}

#do stuff with $xml if not false

It doesn’t come all the time I’ve only seen it on my site like once a week? …but it’s still enough to worry about it. It’s putting an XML feed from last.fm :slight_smile:

Thanks very much Anthony, the code is working now. Hopefully that error doesn’t come back! :slight_smile: