0

Most of the time the URL will return some information, however when no information is returned, I want to return a string 'Empty Result', so not to be passing an empty string to SimpleXmlElement function as this seems to produce an error.

How do I check for a empty/null response from Curl?

    // Get cURL resource
    $curl = curl_init();

    // Set some options - we are passing in a useragent too here
    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => $searchString,
        CURLOPT_USERAGENT => 'Codular Sample cURL Request',
        CURLOPT_FOLLOWLOCATION, true
    ));
    // Send the request & save response to $resp
    $result = curl_exec($curl);

    // Close request to clear up some resources
    curl_close($curl);

    if($result === null)
    {
        return 'Empty Result';
    }

    $doc = new SimpleXmlElement($result, LIBXML_NOCDATA);
Lewisq
  • 23
  • 1
  • 4

2 Answers2

3

Try:

if(!$result || strlen(trim($result)) == 0)
{
    return 'Empty Result';
}

Will return "Empty Result" on failure or if a blank response is encountered.

Alternatively, you could handle your XML errors like so.

Community
  • 1
  • 1
Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
1

Give this a shot

// Get cURL resource
$curl = curl_init();

// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $searchString,
    CURLOPT_USERAGENT => 'Codular Sample cURL Request',
    CURLOPT_FOLLOWLOCATION, true
));
// Send the request & save response to $resp
$result = curl_exec($curl);

// Close request to clear up some resources
curl_close($curl);

if( $result === null || $result == FALSE || $result == '' )
{
    return 'Empty Result';
}

$doc = new SimpleXmlElement($result, LIBXML_NOCDATA);
Josh Mountain
  • 1,888
  • 10
  • 34
  • 51