关于php:当file_get_contents失败时如何跳过代码?


How to skip code when file_get_contents fails?

当我使用如下所示的有效URL时,file_get_contents将返回html代码

1
$html = file_get_contents("http://www.google.com/");

但如果网址无效:

1
$html = file_get_contents("http://www.go1235ogle.com/"); //Invalid URL. This line give Error Message

我的代码将输出错误消息Notice: Trying to get property of non-object

如果file_get_contents无法打开给定的URL,我想隐藏它正在输出的错误消息,并使用if else语句跳过下面的代码。

1
2
3
4
if (FALSE === $html)
{
  //skip the code in here ?
}

但是上面的代码没有帮助。 您能告诉我如何解决此问题吗?


您可以通过添加@来隐藏错误

1
2
3
4
5
6
7
$html = @file_get_contents("http://www.google.com/");
if ($html === FALSE){
  // Error
}
else {
  // No errors
}

资料来源:https://stackoverflow.com/a/272377/1907875


1
2
3
4
5
6
if (FALSE === $html)
{
  // TODO: handle the case when file_get_contents fails
} else {
  // TODO: handle the case when file_get_contents succeeds
}

要摆脱Notice: Trying to get property of non-object,或者通过关闭display_errors完全关闭输出错误消息(在生产环境中推荐),或者将error_reporting设置为较低级别。

但是,您发布的代码不应产生Notice: Trying to get property of non-object


该行不会产生错误,您需要检查其余代码,因为您稍后可能会使用$html


您要执行代码,除非值是false,所以将代码放在if (false !== $html)块中