【问题标题】:Download the contents of a URL in PHP even if it returns a 404在 PHP 中下载 URL 的内容,即使它返回 404
【发布时间】:2011-10-06 19:27:38
【问题描述】:

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

【问题讨论】:

    标签: php http-status-code-404


    【解决方案1】:

    您必须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 流包装器(重新)填充该变量。

    【讨论】:

    • 有趣的方法 - 但你能判断你是收到错误还是成功响应?
    • +1 Gordon 是对的,变量 $http_response_header 包含的正是它在锡上所说的内容,其中显然包括状态码。
    【解决方案2】:

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

    With curl you get the headers and the content separately.

    从 PHP 5.0 开始,您还可以为 file_get_contents 指定上下文,这样您就可以在不依赖 url 的情况下执行此操作(请参阅 Gordon 的回答)。

    【讨论】:

      【解决方案3】:

      请改用cURL。它允许更大的控制,并允许您读取检索到的任何内容和状态代码。

      【讨论】:

        【解决方案4】:

        第一步:查看返回码: $content = file_get_contents("websitelink"); if($content === FALSE) { // handle error here... }

        第 2 步:通过在对 file_get_contents() 的调用之前放置错误控制运算符(即@)来抑制警告:$content = @file_get_contents($site);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-04-22
          • 2014-10-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-13
          相关资源
          最近更新 更多