curl获取标头参数

curl获取标头参数

本文介绍了PHP curl获取标头参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用curl与PHP来获取API调用的标头响应.

I'm using curl with PHP for getting the header response of an API call.

这是我的代码:

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL,            'http://localapi.com/v1/users');
curl_setopt($curl, CURLOPT_HEADER,         true);
curl_setopt($curl, CURLOPT_NOBODY,         true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT,        10);
curl_setopt($curl, CURLOPT_HTTPHEADER,     array("authorization: Basic dmt5MVVTeXg3ZXpKYXVEZGtta2phZThfQ0tXa2tTQkY6"));
$response = curl_exec($curl);

$ response 返回标头:

是否有一种访问单个标头变量(如数组)的方法?

Is there a method for access to the single header variables like an array?

预先感谢您的帮助.

推荐答案

您可以使用 CURLOPT_HEADERFUNCTION .通过为回调提供 $ headers 变量以分配结果,您可以在 curl_exec 完成后将它们作为数组访问.

You can assign a callback for Curl to process the headers in the response using CURLOPT_HEADERFUNCTION. By providing the $headers variable for the callback to assign the results, you can access them as an array after curl_exec has finished.

$headers = [];

curl_setopt($curl, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$headers) {
    $matches = array();

    if ( preg_match('/^([^:]+)\s*:\s*([^\x0D\x0A]*)\x0D?\x0A?$/', $header, $matches) )
    {
        $headers[$matches[1]][] = $matches[2];
    }

    return strlen($header);
});

curl_exec($curl);

$ headers 现在将包含响应头的关联数组

$headers will now contain an associative array of the response headers

这篇关于PHP curl获取标头参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 01:33