如何解析cURL返回的header?

How to parse the header returned by cURL?

我正在尝试使用 cURL 与 API 通信。其中一种方法要求我传递 ININ-ICWS-CSRF-Token header(即 WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA=)和 Set-Cookie(即 icws_904586002=bf7c7783-6766-4c4f-862b-48f25a9a3741)的值,所以我需要提取它们,以便稍后在我的代码中传递它们。

这是我从 cURL/API 响应中提取 header 和 body 所做的工作:

$respond = curl_exec($ch);

//throw cURL exception
if($respond === false){
    $errorNo = curl_errno($ch);
    $errorMessage = curl_error($ch);

    throw new ApiException($errorMessage, $errorNo);
}    

list($header, $body) = explode("\r\n\r\n", $respond, 2);
echo '<pre>';
print_r($header);
echo '</pre>';

这是$header值的内容:

HTTP/1.1 201 Created
ININ-ICWS-CSRF-Token: WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA=
ININ-ICWS-Session-ID: 904586002
Set-Cookie: icws_904586002=bf7c7783-6766-4c4f-862b-48f25a9a3741; Path=/icws/904586002
Location: /icws/904586002/connection
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Type: application/vnd.inin.icws+JSON; charset=utf-8
Date: Wed, 06 May 2015 17:13:44 GMT
Server: HttpPluginHost
Content-Length: 237

我想获得 return 这样的结果

the value of "ININ-ICWS-CSRF-Token" is "WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA="
the value of the "cookie" is "ININ-ICWS-CSRF-Token: WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA="
<?php

$myHeader = <<< LOL
HTTP/1.1 201 Created
ININ-ICWS-CSRF-Token: WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA=
ININ-ICWS-Session-ID: 904586002
Set-Cookie: icws_904586002=bf7c7783-6766-4c4f-862b-48f25a9a3741; Path=/icws/904586002
Location: /icws/904586002/connection
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Type: application/vnd.inin.icws+JSON; charset=utf-8
Date: Wed, 06 May 2015 17:13:44 GMT
Server: HttpPluginHost
Content-Length: 237
LOL;

preg_match_all('/(.*?Token): (.*?)\s+/', $myHeader, $matches, PREG_PATTERN_ORDER);
$tokenName = $matches[1][0];
$token = $matches[2][0];

echo <<< LOL
the value of "$tokenName" is "$token"
the value of the "cookie" is "$tokenName: $token"
LOL;

?>

您可以使用http_parse_headers函数解析headers。

$hdr_array = http_parse_headers($header);

foreach ($hdr_array as $name => $value) {
    echo "The value of '$name' is '$value'<br>";
}

如果你没有http_parse_headers,你可以使用 Pedro Lobito 的答案中的代码。