使用curl获取HTTP标头并保存到变量
问题描述:
我使用这个抢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手册,但不能工作了
答
preg_match('~^(Expires:.+?)$~ism', $headers, $result);
return $result[1];
+0
不知道为什么这是'1',但是'sm'修饰符和括号是必需的吗? – 2011-11-22 16:58:44
答
您可以使用PHP的get_headers($网址,1)函数返回数组中的所有头信息,如果你设置第二可选PARAM到1(不为零),然后将其解析成一个关联数组等:
array(
[...] => ...,
[Expires] => 'what you need',
[...] => ...
)
拆分上换行符文本,遍历所有行,直到遇到一个字符串,开头“过期:”,削减前9个字符,你已经得到了答案。 – CodeCaster