如何解析cURL返回的头? [英] How to parse the header returned by cURL?
问题描述
我想使用cURL与API沟通。其中一个方法要求我通过了 ININ-ICWS-CSRF令牌
头的值(即 WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA =
)和设置Cookie
(即 icws_904586002 = bf7c7783-6766-4c4f-862B-48f25a9a3741
),所以我需要提取它们,所以我以后可以在我的代码中传递它们。
I am trying to communicate to an API using cURL. One of the methods require that I pass the value of the ININ-ICWS-CSRF-Token
header (ie. WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA=
) and the Set-Cookie
(ie. icws_904586002=bf7c7783-6766-4c4f-862b-48f25a9a3741
) so I need to extract them so I can pass them later in my code.
这里是我从cURL / API提取标题和正文响应: p>
Here is what I did to extract the header and the body from the cURL/API respond:
$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
我想要返回类似的结果
the value of "ININ-ICWS-CSRF-Token" is "WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA="
the value of the "cookie" is "ININ-ICWS-CSRF-Token: WAhtYWxoYXlla1dBY2NvUkRJWCQxZmUxZWFhZS0xZTE0LTQyNGYtYjdhZS0zNmZjN2MxYWJmODBYCjEwLjAuNC4xNjA="
推荐答案
您可以使用 http_parse_headers
函数来解析头。
You can use the http_parse_headers
function to parse the 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的回答中的代码。
If you don't have http_parse_headers
, you can use the code in Pedro Lobito's answer.
这篇关于如何解析cURL返回的头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!