【发布时间】:2011-10-06 19:27:38
【问题描述】:
我想使用 PHP 下载 URL 的内容,即使 HTTP 响应代码是 404。file_get_contents 会出错,我无法使用 Google 找到答案。我该怎么做?
【问题讨论】:
我想使用 PHP 下载 URL 的内容,即使 HTTP 响应代码是 404。file_get_contents 会出错,我无法使用 Google 找到答案。我该怎么做?
【问题讨论】:
您必须configure the stream wrapper 才能忽略错误:
ignore_errors
boolean即使是失败状态码也能获取内容。默认为FALSE
换句话说,做
echo file_get_contents(
'http://stackoverflow.com/foo/bar',
false,
stream_context_create([
'http' => [
'ignore_errors' => true,
],
])
);
你会得到 404 页面。
如果您希望这是 HTTP 流的默认行为,请使用
stream_context_set_default(
array('http' => array(
'ignore_errors' => true)
)
);
任何使用 HTTP 流包装器的调用都将使用这些设置,例如你可以简单地做
echo file_get_contents('http://stackoverflow.com/foo/bar');
如果你也想获得response header,就这样做
print_r($http_response_header);
通话后。每次调用后都会使用 http 流包装器(重新)填充该变量。
【讨论】:
默认情况下file_get_contents 只返回 HTTP 200 响应的内容。
With curl you get the headers and the content separately.
从 PHP 5.0 开始,您还可以为 file_get_contents 指定上下文,这样您就可以在不依赖 url 的情况下执行此操作(请参阅 Gordon 的回答)。
【讨论】:
请改用cURL。它允许更大的控制,并允许您读取检索到的任何内容和状态代码。
【讨论】:
第一步:查看返回码:
$content = file_get_contents("websitelink");
if($content === FALSE) { // handle error here... }
第 2 步:通过在对 file_get_contents() 的调用之前放置错误控制运算符(即@)来抑制警告:$content = @file_get_contents($site);
【讨论】: