Ignoring errors in file_get_contents HTTP wrapper?

爱⌒轻易说出口 提交于 2019-11-28 00:49:29

If you don't want file_get_contents to report HTTP errors as PHP Warnings, then this is the clean way to do it, using a stream context (there is something specifically for that):

$context = stream_context_create(array(
    'http' => array('ignore_errors' => true),
));

$result = file_get_contents('http://your/url', false, $context);

The simplest solution if you're okay with just bailing out, would be:

if (empty($thesaurus_search)) { 
   return;
} else {
   //process with value
}

To more fully handle it, looking at the API, it looks like you should be checking the response header, e.g.:

$thesaurus_search="http://words.bighugelabs.com/api/2/0089388bb57f/".$this->formatted_query."/php";
$result_thesaurus=file_get_contents($thesaurus_search);
if ($http_response_header[0] = 'HTTP/1.1 200 OK') {
    //code to handle words
} else {
    // do something else?
}

If I understand you properly you are trying to make an API call to http://words.bighugelabs.com. You need cURL to achieve this so if you have cURL installed then this code will work for you.

$ch = curl_init();
$thesaurus_search="http://words.bighugelabs.com/api/2/0089388bb57f/".$this->formatted_query."/php";
$options = array();
$options[CURLOPT_URL] = $thesaurus_search;
$options[CURLOPT_RETURNTRANSFER] = true;
curl_setopt_array($ch, $options);

// Print result.
print_r(curl_close($ch));

You might try curl:

function curl_get_contents($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
    curl_setopt($ch, CURLOPT_MAXREDIRS, 2); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!