我写了这样的PHP代码

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

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

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

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


当前回答

你可以在前面加上@: $content = @file_get_contents($site);

这将抑制任何警告-谨慎使用!参见错误控制操作符

编辑:当你删除“http://'”时,你不再寻找一个网页,而是在你的磁盘上一个名为“www.google.....”的文件。

其他回答

你可以在前面加上@: $content = @file_get_contents($site);

这将抑制任何警告-谨慎使用!参见错误控制操作符

编辑:当你删除“http://'”时,你不再寻找一个网页,而是在你的磁盘上一个名为“www.google.....”的文件。

您还可以将错误处理程序设置为调用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();

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

就像这样:

public function get($curl,$options){
    $context = stream_context_create($options);
    $file = @file_get_contents($curl, false, $context);
    $str1=$str2=$status=null;
    sscanf($http_response_header[0] ,'%s %d %s', $str1,$status, $str2);
    if($status==200)
        return $file        
    else 
        throw new \Exception($http_response_header[0]);
}

我是这样做的……不需要try-catch块…最好的解决方案总是最简单的……享受吧!

$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) { 
   echo "SUCCESS";
} else { 
   echo "FAILED";
} 

最好的方法是设置自己的错误和异常处理程序,这些处理程序将做一些有用的事情,如将其记录在文件中或通过电子邮件发送关键的错误和异常处理程序。 http://www.php.net/set_error_handler