簡體   English   中英

使用file_get_contents時忽略Content-Length標頭

[英]Ignore Content-Length header when using file_get_contents

我需要獲取頁面的內容,該頁面始終發送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
)

正如Optimist指出的那樣,該問題與頭無關,而是我沒有將任何User-Agent頭發送到服務器。

即使服務器始終返回Content-Length: 0 ,在發送User-Agent標頭后, file_get_contents工作。

奇怪的。

我相信,沒有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);
    }
}

然后僅剪切標題即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM