我写了这样的PHP代码
$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
但是当我从$site中删除“http://”时,我得到以下警告:
警告: file_get_contents (www.google.com) (函数。file-get-contents]:失败 打开水流:
我试过,试过,但没成功。
我写了这样的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);
}
其他回答
下面是我的处理方法:
$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();
}
在使用file_get_contents()之前,应该使用file_exists()函数。 这样可以避免php警告。
$file = "path/to/file";
if(file_exists($file)){
$content = file_get_contents($file);
}
就像这样:
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]);
}
第一步:检查返回代码:if($content === FALSE){//处理错误这里…}
第二步:通过在file_get_contents()调用前放置一个错误控制操作符(即@)来抑制警告: $content = @file_get_contents($site);
这将尝试获取数据,如果它不起作用,它将捕获错误,并允许您在捕获范围内执行所需的任何操作。
try {
$content = file_get_contents($site);
} catch(\Exception $e) {
return 'The file was not found';
}