使用file_get_contents时忽略Content-Length标头

时间:2012-02-18 18:08:43

标签: php http-headers file-get-contents http-content-length

我需要获取页面的内容,该页面始终发送Content-Length: 0标题,但页面永远不会为空。

file_get_contents(url)只返回一个空字符串。

页面返回的整个标题是:

HTTP/1.1 200 OK
X-Powered-By: PHP/5.3.10
Expires: Mon, 26 Jul 1997 05:00:00 GMT
Last-Modified: Sat, 18 Feb 2012 18:14:59 GMT
Cache-Control: no-store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Pragma: no-cache
Content-Type: text/html; charset=UTF-8
Content-Length: 0
Date: Sat, 18 Feb 2012 18:14:59 GMT
Server: lighttpd

是否可以使用file_get_contents并忽略标题或我是否需要使用curl?

修改

get_headers(url)输出(使用print_r):

Array
(
    [0] => HTTP/1.0 200 OK
    [1] => X-Powered-By: PHP/5.3.10
    [2] => Content-type: text/html
    [3] => Content-Length: 0
    [4] => Connection: close
    [5] => Date: Sat, 18 Feb 2012 22:39:52 GMT
    [6] => Server: lighttpd
)

2 个答案:

答案 0 :(得分:0)

我相信,没有HTTP级别的功能无法读取这样的答案。因为它是不正确的HTTP答案,它说“我的身体是空的,不要读它”

你肯定需要你自己的基于fread的功能,它会在视觉上读取套接字。像这样:

$aURL    = parse_url($sURL);

if ($iHandle = fsockopen($aURL["host"], 80, $iError, $sError))
{
    $sQuery = substr($sURL, strpos($sURL, $aURL["host"]) + strlen($aURL["host"]));

    $sOut   = "GET " . (($sQuery != "") ? $sQuery : "/") . " HTTP/1.1\r\n";
    $sOut  .= "Host: " . $aURL["host"] . "\r\n";
    $sOut  .= "Connection: Close\r\n\r\n";

    fputs($iHandle, $sOut);

    while (!feof($iHandle))
    {
        $sResult .= fread($iHandle, 1024);
    }
}

然后切断标题。

答案 1 :(得分:0)

正如Optimist所说,这个问题与标题无关,而是我没有向服务器发送任何User-Agent标题。

发送User-Agent标头后,

file_get_contents工作正常,即使服务器始终返回Content-Length: 0

怪异。

相关问题