[英]PHP curl get header parameters
I'm using curl with PHP for getting the header response of an API call. 我正在使用curl与PHP来获取API调用的标头响应。
This is my code: 这是我的代码:
$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);
The $response
returna the header: $response
返回标题:
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: ;
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.31 X-Rate-Limit-限制:1个剩余X速率限制:0个X速率限制重置:0个X分页总数:1个X分页页数:1个X分页当前页数:1个X-每页分页:20链接:; rel=self Content-Type: application/json;
rel = self内容类型:application / json; charset=UTF-8 1
字符集= UTF-8 1
Is there a method for access to the single header variables like an array? 有没有一种方法可以访问单个标头变量(如数组)?
Thanks in advance for the help. 先谢谢您的帮助。
You can assign a callback for Curl to process the headers in the response using CURLOPT_HEADERFUNCTION . 您可以使用CURLOPT_HEADERFUNCTION为Curl分配一个回调以处理响应中的标头。 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_exec
完成后将它们作为数组访问。
$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
will now contain an associative array of the response headers $headers
现在将包含响应头的关联数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.