我写了这样的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]:失败 打开水流:
我试过,试过,但没成功。
当前回答
这将尝试获取数据,如果它不起作用,它将捕获错误,并允许您在捕获范围内执行所需的任何操作。
try {
$content = file_get_contents($site);
} catch(\Exception $e) {
return 'The file was not found';
}
其他回答
最好的方法是设置自己的错误和异常处理程序,这些处理程序将做一些有用的事情,如将其记录在文件中或通过电子邮件发送关键的错误和异常处理程序。 http://www.php.net/set_error_handler
一种替代方法是抑制错误并抛出稍后可以捕获的异常。如果在代码中有多个对file_get_contents()的调用,这尤其有用,因为您不需要手动抑制和处理所有这些调用。相反,可以在一个try/catch块中对该函数进行多次调用。
// Returns the contents of a file
function file_contents($path) {
$str = @file_get_contents($path);
if ($str === FALSE) {
throw new Exception("Cannot access '$path' to read contents.");
} else {
return $str;
}
}
// Example
try {
file_contents("a");
file_contents("b");
file_contents("c");
} catch (Exception $e) {
// Deal with it.
echo "Error: " , $e->getMessage();
}
if (!file_get_contents($data)) {
exit('<h1>ERROR MESSAGE</h1>');
} else {
return file_get_contents($data);
}
这将尝试获取数据,如果它不起作用,它将捕获错误,并允许您在捕获范围内执行所需的任何操作。
try {
$content = file_get_contents($site);
} catch(\Exception $e) {
return 'The file was not found';
}
你可以在前面加上@: $content = @file_get_contents($site);
这将抑制任何警告-谨慎使用!参见错误控制操作符
编辑:当你删除“http://'”时,你不再寻找一个网页,而是在你的磁盘上一个名为“www.google.....”的文件。