2011-11-22 33 views
3

我使用這個搶XML飼料和HTTP頭使用curl獲取HTTP標頭並保存到變量

// Initiate the curl session 
$ch = curl_init(); 

// Set the URL 
curl_setopt($ch, CURLOPT_URL, $url); 

// Allow the headers 
curl_setopt($ch, CURLOPT_HEADER, true); 

// Return the output instead of displaying it directly 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

// Execute the curl session 
$output = curl_exec($ch); 

// Close the curl session 
curl_close($ch); 

// Cache feed 
file_put_contents($filename, $output); 

// XML to object 
$output = simplexml_load_string($output); 

// Return the output as an array 
return $output; 

,並返回這些頭

HTTP/1.1 200 OK 
Cache-Control: public, max-age=30 
Content-Length: 5678 
Content-Type: text/xml 
Expires: Tue, 22 Nov 2011 15:12:16 GMT 
Last-Modified: Tue, 22 Nov 2011 15:11:46 GMT 
Vary: * 
Server: Microsoft-IIS/7.0 
Set-Cookie: ASP.NET_SessionId=1pfijrmsqndn5ws3124csmhe; path=/; HttpOnly 
Data-Last-Updated: 11/22/2011 15:11:45 
X-AspNet-Version: 4.0.30319 
X-Powered-By: ASP.NET 
Date: Tue, 22 Nov 2011 15:11:46 GMT 

我只希望它返回HTTP標頭的一部分,即

Expires: Tue, 22 Nov 2011 15:12:16 GMT 

並將其保存到變量中,我該怎麼做?我一直在尋找通過PHP手冊,但不能工作了

+6

拆分上換行符文本,遍歷所有行,直到遇到一個字符串,開頭「過期:」,削減前9個字符,你已經得到了答案。 – CodeCaster

回答

3
preg_match('~^(Expires:.+?)$~ism', $headers, $result); 

return $result[1]; 
+0

不知道爲什麼這是'1',但是'sm'修飾符和括號是必需的嗎? – 2011-11-22 16:58:44

2

您可以使用PHP的get_headers($網址,1)函數返回數組中的所有頭信息,如果你設置第二可選PARAM到1(不爲零),然後將其解析成一個關聯數組等:

array(
    [...] => ..., 
    [Expires] => 'what you need', 
    [...] => ... 
) 

http://php.net/manual/en/function.get-headers.php