c.hill 的 anwser 很棒,但如果第一个响应是 301 或 302,代码将无法处理 - 在这种情况下,只有第一个标头将添加到 get_header_from_curl_response() 返回的数组中。
我已经更新了函数以返回一个包含每个标题的数组。
首先,我使用这些行创建一个仅包含标题内容的变量
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($a, 0, $header_size);
比我将 $header 传递给新的 get_headers_from_curl_response() 函数:
static function get_headers_from_curl_response($headerContent)
{
$headers = array();
// Split the string on every "double" new line.
$arrRequests = explode("\r\n\r\n", $headerContent);
// Loop of response headers. The "count() -1" is to
//avoid an empty row for the extra line break before the body of the response.
for ($index = 0; $index < count($arrRequests) -1; $index++) {
foreach (explode("\r\n", $arrRequests[$index]) as $i => $line)
{
if ($i === 0)
$headers[$index]['http_code'] = $line;
else
{
list ($key, $value) = explode(': ', $line);
$headers[$index][$key] = $value;
}
}
}
return $headers;
}
此函数将采用如下标题:
HTTP/1.1 302 Found
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Location: http://www.website.com/
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Date: Sun, 08 Sep 2013 10:51:39 GMT
Connection: close
Content-Length: 16313
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Date: Sun, 08 Sep 2013 10:51:39 GMT
Connection: close
Content-Length: 15519
并返回一个这样的数组:
(
[0] => Array
(
[http_code] => HTTP/1.1 302 Found
[Cache-Control] => no-cache
[Pragma] => no-cache
[Content-Type] => text/html; charset=utf-8
[Expires] => -1
[Location] => http://www.website.com/
[Server] => Microsoft-IIS/7.5
[X-AspNet-Version] => 4.0.30319
[Date] => Sun, 08 Sep 2013 10:51:39 GMT
[Connection] => close
[Content-Length] => 16313
)
[1] => Array
(
[http_code] => HTTP/1.1 200 OK
[Cache-Control] => private
[Content-Type] => text/html; charset=utf-8
[Server] => Microsoft-IIS/7.5
[X-AspNet-Version] => 4.0.30319
[Date] => Sun, 08 Sep 2013 10:51:39 GMT
[Connection] => close
[Content-Length] => 15519
)
)