Ignoring errors in file_get_contents HTTP wrapper?

孤者浪人 提交于 2019-11-26 21:32:01

问题


The following code is to query an online thesaurus for a search engine I'm building as a college project, but I'm having problems with file_get_contents "failed to open stream" errors. When I send a word the thesaurus doesn't recognize, it throws up an error. I'm trying to write a piece of code that will ignore the error and just proceed without the information.

$thesaurus_search="http://words.bighugelabs.com/api/2/0089388bb57f/".$this->formatted_query."/php";
$result_thesaurus=file_get_contents($thesaurus_search);

I tried:

if (file_get_contents($thesaurus_search) != NULL)
{ // do stuff }

...but its not working because it still returns some sort of string.

What can I do to handle such cases?


回答1:


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);



回答2:


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?
}



回答3:


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));



回答4:


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;
}


来源:https://stackoverflow.com/questions/11475657/ignoring-errors-in-file-get-contents-http-wrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!