我写了这样的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前面加上@, 即:

$content = @file_get_contents($site); 

其他回答

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
}

就像这样:

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 {
    $content = file_get_contents($site);
} catch(\Exception $e) {
    return 'The file was not found';
}

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

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

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

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