我写了这样的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]:失败 打开水流:
我试过,试过,但没成功。
当前回答
下面是我的处理方法:
$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();
}
其他回答
你可以在前面加上@: $content = @file_get_contents($site);
这将抑制任何警告-谨慎使用!参见错误控制操作符
编辑:当你删除“http://'”时,你不再寻找一个网页,而是在你的磁盘上一个名为“www.google.....”的文件。
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”就可以捕获它。
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
}
我是这样做的……不需要try-catch块…最好的解决方案总是最简单的……享受吧!
$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) {
echo "SUCCESS";
} else {
echo "FAILED";
}