在PHP中下载URL的内容,即使它返回404


Download the contents of a URL in PHP even if it returns a 404

我想使用PHP下载URL的内容,即使HTTP响应代码是404。file_get_contents会出错,我用谷歌也找不到答案。我该怎么做呢?

你必须配置流包装器来忽略错误:

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');

如果您还想获得响应头,只需执行

print_r($http_response_header);

。该变量在每次调用后使用http流包装器(重新)填充。

默认情况下,file_get_contents只返回HTTP 200响应的内容。

使用curl可以分别获得标题和内容。

从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);