在此线程中借鉴@Geoffrey 出色的答案...
该线程提供的其他一些解决方案没有正确执行此操作。
- 当打开或服务器以 100 代码响应时,拆分打开
\r\n\r\n
是不可靠的。CURLOPT_FOLLOWLOCATION
- 通过检测标头的大小
CURLINFO_HEADER_SIZE
也并不总是可靠的,尤其是在使用代理或在某些相同的重定向场景中。
获取标头最可靠的方法是使用CURLOPT_HEADERFUNCTION
. 然后你可以删除curl_setopt($ch, CURLOPT_HEADER, 1);
,你的身体会很干净,没有标题。
这是使用 PHP 闭包执行此操作的一种非常简洁的方法。它还将所有标头转换为小写,以便跨服务器和 HTTP 版本进行一致处理。
$ch = curl_init();
$headers = [];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Run the following function for each header received
// Note: Does NOT handle multiple instances of the same header. Later one will overwrite.
// Consider handling that scenario if you need it.
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header) use (&$headers) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) >= 2)
$headers[strtolower(trim($header[0]))] = trim($header[1]);
return $len;
});
$data = curl_exec($ch);
print_r($headers);