Avatar ·

如何在PHP cURL中通过一次请求获取HTTP响应头和响应体?

大家好!我正在用PHP编写一个使用cURL的解析器。我不仅需要获取页面内容(响应体),还需要获取HTTP头(例如Content-Type、状态码、重定向时的Location)。

问题在于,当我使用curl_exec()时,我只得到响应体。如果我启用选项CURLOPT_HEADER => true,结果会同时输出头和体,必须通过explode()手动解析,这非常不方便。

以下是我当前的代码:

$ch = curl_init('https://example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
curl_close($ch);

// 不得不笨拙地分割
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

这种方法虽然有效,但我觉得它很粗糙。而且