如何解析cURL返回的头?

时间:2015-05-06 17:21:56

标签: php curl icws

我正在尝试使用cURL与API进行通信。其中一种方法要求我传递jQuery.each(result.address, function(key, val) { console.log(val.city); }); 标题(即。ININ-ICWS-CSRF-Token)和WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA=(即Set-Cookie)的值,因此我需要提取它们我可以稍后在我的代码中传递它们。

以下是我从cURL / API中提取标题和正文的做法:

icws_904586002=bf7c7783-6766-4c4f-862b-48f25a9a3741

这是$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

2 个答案:

答案 0 :(得分:3)

您可以使用http_parse_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答案中的代码。

答案 1 :(得分:0)

<?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;

?>