PHP curl获取标头参数 [英] PHP curl get header parameters
问题描述
我正在使用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
返回标头:
HTTP/1.1 200 OK日期:2016年6月15日,星期三13:48:43 GMT服务器:Apache/2.4.18(Unix)PHP/5.5.31 X-Powered-By:PHP/5.5.31X-Rate-Limit-Limit:1 X-Rate-Limit-Remaining:0 X-Rate-Limit-Reset:0X分页总数:1 X分页总数:1X-Pagination-当前页:1 X-Pagination-每页:20链接:;rel = self内容类型:application/json;charset = UTF-8 1
HTTP/1.1 200 OK Date: Wed, 15 Jun 2016 13:48:43 GMT Server: Apache/2.4.18 (Unix) PHP/5.5.31 X-Powered-By: PHP/5.5.31 X-Rate-Limit-Limit: 1 X-Rate-Limit-Remaining: 0 X-Rate-Limit-Reset: 0 X-Pagination-Total-Count: 1 X-Pagination-Page-Count: 1 X-Pagination-Current-Page: 1 X-Pagination-Per-Page: 20 Link: ; rel=self Content-Type: application/json; charset=UTF-8 1
是否有一种访问单个标头变量(如数组)的方法?
Is there a method for access to the single header variables like an array?
预先感谢您的帮助.
推荐答案
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获取标头参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!