如何处理PHP中的file_get_contents()函数警告?

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:58   2918   0

本文翻译自:How can I handle the warning of file_get_contents() function in PHP?

I wrote a PHP code like this 我写了这样的PHP代码

$site="http://www.google.com";
$content = file_get_content($site);
echo $content;

But when I remove "http://" from $site I get the following warning: 但是,当我从$site删除“ http://”时,出现以下警告:

Warning: file_get_contents(www.google.com) [function.file-get-contents]: failed to open stream: 警告:file_get_contents(www.google.com)[function.file-get-contents]:无法打开流:

I tried try and catch but it didn't work. 我想trycatch ,但没有奏效。


#1楼

参考:https://stackoom.com/question/18qv/如何处理PHP中的file-get-contents-函数警告


#2楼

My favourite way to do this is fairly simple: 我最喜欢的方法很简单:

if (!$data = file_get_contents("http://www.google.com")) {
      $error = error_get_last();
      echo "HTTP request failed. Error was: " . $error['message'];
} else {
      echo "Everything went better than expected";
}

I found this after experimenting with the try/catch from @enobrev above, but this allows for less lengthy (and IMO, more readable) code. 我在try/catch上述@enobrev的try/catch之后发现了这一点,但这可以减少冗长的代码(以及IMO,更易读)。 We simply use error_get_last to get the text of the last error, and file_get_contents returns false on failure, so a simple "if" can catch that. 我们仅使用error_get_last来获取上一个错误的文本,而file_get_contents在失败时返回false,因此可以使用简单的“ if”来捕获错误。


#3楼

Here's how I handle that: 这是我的处理方式:

$this->response_body = @file_get_contents($this->url, false, $context);
if ($this->response_body === false) {
    $error = error_get_last();
    $error = explode(': ', $error['message']);
    $error = trim($error[2]) . PHP_EOL;
    fprintf(STDERR, 'Error: '. $error);
    die();
}

#4楼

function custom_file_get_contents($url) {
    return file_get_contents(
        $url,
        false,
        stream_context_create(
            array(
                'http' => array(
                    'ignore_errors' => true
                )
            )
        )
    );
}

$content=FALSE;

if($content=custom_file_get_contents($url)) {
    //play with the result
} else {
    //handle the error
}

#5楼

Since PHP 4 use error_reporting() : 由于PHP 4使用error_reporting()

$site="http://www.google.com";
$old_error_reporting = error_reporting(E_ALL ^ E_WARNING);
$content = file_get_content($site);
error_reporting($old_error_reporting);
if ($content === FALSE) {
    echo "Error getting '$site'";
} else {
    echo $content;
}

#6楼

You can prepend an @: $content = @file_get_contents($site); 您可以在@前面加上: $content = @file_get_contents($site);

This will supress any warning - use sparingly! 这将禁止任何警告- 谨慎使用! . See Error Control Operators 请参阅错误控制运算符

Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....." 编辑:当您删除“ http://”时,您不再在寻找网页,而是在磁盘上名为“ www.google .....”的文件。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP