由于该函数返回 HTTP 响应标头,因此您应该检查是否'Transfer-Encoding'
is 'chunked'
然后解码分块编码的字符串。
在伪代码中:
CALL parse_http_header
IF 'Transfer-Encoding' IS 'chunked'
CALL decode_chunked
解析HTTP响应头:
下面是将 HTTP 响应头解析为关联数组的函数。
function parse_http_header($str)
{
$lines = explode("\r\n", $str);
$head = array(array_shift($lines));
foreach ($lines as $line) {
list($key, $val) = explode(':', $line, 2);
if ($key == 'Set-Cookie') {
$head['Set-Cookie'][] = trim($val);
} else {
$head[$key] = trim($val);
}
}
return $head;
}
该函数将返回一个像这样的数组:
Array
(
[0] => HTTP/1.1 200 OK
[Expires] => Tue, 31 Mar 1981 05:00:00 GMT
[Content-Type] => text/html; charset=utf-8
[Transfer-Encoding] => chunked
[Set-Cookie] => Array
(
[0] => k=10.34; path=/; expires=Sat, 09-Jun-12 01:58:23 GMT; domain=.example.com
[1] => guest_id=v1%3A13; domain=.example.com; path=/; expires=Mon, 02-Jun-2014 13:58:23 GMT
)
[Content-Length] => 43560
)
请注意如何Set-Cookie
标头解析为数组。您稍后需要解析 cookie,将 URL 与需要发送的 cookie 相关联。
解码分块编码的字符串
下面的函数将分块编码的字符串作为参数,并返回
解码后的字符串。
function decode_chunked($str) {
for ($res = ''; !empty($str); $str = trim($str)) {
$pos = strpos($str, "\r\n");
$len = hexdec(substr($str, 0, $pos));
$res.= substr($str, $pos + 2, $len);
$str = substr($str, $pos + 2 + $len);
}
return $res;
}
// Given the string in the question, the function above will returns:
//
// This is the data in the first chunk
// and this is the second one
// consequence