file_get_contents会优雅地失败吗?
答
任何使用HTTP包装器访问远程文件的函数,就好像它是本地的,将自动生成本地作用域中名为$http_response_header
的局部变量。您可以访问该变量以查找有关在远程文件上调用fopen
,file_get_contents
...时发生的情况的信息。
您可以使用@
来抑制警告:@file_get_contents
。
如果你不关心是什么错误,你可以使用@file_get_contents
,并将结果false
比较:
$content = @file_get_contents(url);
if ($content === false) { /* failure */ } else { /* success */ }
答
你可以做一个额外的(HEAD)的要求,找出第一,例如
$response = get_headers($url);
if($response[1] === 'HTTP/1.1 200 OK') {
$content = file_get_contents($url);
}
或者你可以告诉file_get_contents
忽略任何错误,并通过修改流上下文力取$url
结果:
echo file_get_contents(
'http://www.example.com/foo.html',
FALSE,
stream_context_create(array('http'=>array('ignore_errors' => TRUE)))
)
正是我需要的,谢谢! – 2016-02-15 01:32:30