我写了这样的PHP代码

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

但是当我从$site中删除“http://”时,我得到以下警告:

警告: file_get_contents (www.google.com) (函数。file-get-contents]:失败 打开水流:

我试过,试过,但没成功。


当前回答

在使用file_get_contents()之前,应该使用file_exists()函数。 这样可以避免php警告。

$file = "path/to/file";

if(file_exists($file)){
  $content = file_get_contents($file);
}

其他回答

if (!file_get_contents($data)) {
  exit('<h1>ERROR MESSAGE</h1>');
} else {
      return file_get_contents($data);
}

我最喜欢的方法很简单:

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

我在尝试上面@enobrev的try/catch后发现了这一点,但这允许更短的长度(在我看来,更可读)代码。我们简单地使用error_get_last来获取最后一个错误的文本,失败时file_get_contents返回false,因此简单的“if”就可以捕获它。

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

最简单的方法是在file_get_contents前面加上@, 即:

$content = @file_get_contents($site); 

您还可以将错误处理程序设置为调用Exception的匿名函数,并对该异常使用try / catch。

set_error_handler(
    function ($severity, $message, $file, $line) {
        throw new ErrorException($message, $severity, $severity, $file, $line);
    }
);

try {
    file_get_contents('www.google.com');
}
catch (Exception $e) {
    echo $e->getMessage();
}

restore_error_handler();

似乎有很多代码来捕捉一个小错误,但如果你在整个应用程序中使用异常,你只需要这样做一次,在顶部的方式(在包含的配置文件中,例如),它会将你所有的错误转换为异常。