2012-04-01 116 views
0

我正在使用get_headers()並且我想返回內容長度。在下面的數組中,內容長度是鍵數9,但是我發現內容長度並不總是鍵數9.我不確定它爲什麼不總是相同的鍵?如何搜索數組並始終返回內容長度,無論它是什麼密鑰?正如我在一個函數中使用這個,所以每次文件的實際文件大小都是不同的。我的示例代碼如下。提前致謝。檢查數組中的鍵php

Array ([0] => HTTP/1.0 200 OK [1] => Server: Apache [2] => Pragma: public [3] => Last-Modified: Sun, 01 Apr 2012 07:59:46 GMT [4] => ETag: "1333267186000" [5] => Content-Type: text/javascript [6] => Cache-Control: must-revalidate, max-age=0, post-check=0, pre-check=0 [7] => Expires: Sun, 01 Apr 2012 10:27:26 GMT [8] => Date: Sun, 01 Apr 2012 10:27:26 GMT [9] => Content-Length: 31650 [10] => Connection: close [11] => Set-Cookie: JSESSIONID=M0V4NTTVSIB4WCRHAWVSFGYKE2C0UIV0; path=/ [12] => Set-Cookie: DYN_USER_ID=2059637079; path=/ [13] => Set-Cookie: DYN_USER_CONFIRM=6c6a03988da3de6d704ce37a889b1ec8; path=/ [14] => Set-Cookie: BIGipServerdiy_pool=637871882.20480.0000; path=/) 

function headInfo($url) { 
    $header = get_headers($url); 
    $fileSize = $header[9]; 
    return array($header, $fileSize); 
} 

回答

4

http://php.net/get_headers

第二個參數:

如果可選格式參數被設置爲非零值,get_headers()解析響應,並設置數組的鍵。

所以,只要傳遞1作爲第二個參數,$ header ['Content-Length']就是你以後的樣子。

+0

現貨,使其$頭= get_headers($網址,1),你回來的關聯數組。然後你可以查看關鍵值。 – 2012-04-01 10:43:39

0

如果您查看get_headers()函數文檔,您可能會注意到,還有第二個(默認)參數可用於指定輸出格式。

$hdr = get_headers($url, 1); 
echo("Content-length: " . $hdr["Content-length"]); 

1 - 表示函數將返回關聯數組。

0

基本上

array get_headers (string $url [, int $format = 0 ]) 

實施例:

get_headers($url,true); 

會給你關聯數組

詳細

<?php 
$url = 'http://www.example.com'; 

print_r(get_headers($url)); 

print_r(get_headers($url, 1)); 
?> 

這將產生

Array 
(
    [0] => HTTP/1.1 200 OK 
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT 
    [2] => Server: Apache/1.3.27 (Unix) (Red-Hat/Linux) 
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT 
    [4] => ETag: "3f80f-1b6-3e1cb03b" 
    [5] => Accept-Ranges: bytes 
    [6] => Content-Length: 438 
    [7] => Connection: close 
    [8] => Content-Type: text/html 
) 

Array 
(
    [0] => HTTP/1.1 200 OK 
    [Date] => Sat, 29 May 2004 12:28:14 GMT 
    [Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux) 
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT 
    [ETag] => "3f80f-1b6-3e1cb03b" 
    [Accept-Ranges] => bytes 
    [Content-Length] => 438 
    [Connection] => close 
    [Content-Type] => text/html 
) 

希望它有助於