php, From fsockopen result, how to remove chunked data and get data
the result of reponse is like this
HTTP/1.1 200 OK
Date: Fri, 11 Feb 2011 06:59:47 GMT
Server: Apache
S开发者_如何学Pythonet-Cookie: id%22%3Bs%3A32%3A%223c38c56b3def2530014336c922ee0bfc%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%2269.162.119.226%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A0%3A%22%22%3Bs%3A13%3A%22last_activity%22%3Bs%3A10%3A%221297407587%22%3B%7Dcd356ca12b8d395b49603cb3eb34f786; expires=Fri, 11-Feb-2011 08:59:47 GMT; path=/ Set-Cookie: vaave_session=a%3A3Bs%3A32%3A%223c38c56b3def2530014336c922ee0bfc%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%2269.162.119.226%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A0%3A%22%22%3Bs%3A13%3A%22last_activity%22%3Bs%3A10%3A%221297407587%22%3Bs%3A2%3A%22tz%22%3Bs%3A13%3A%22Asia%2FCalcutta%22%3B%7Daadf6cb5ad21eae3c04e24cf00b3ea16; expires=Fri, 11-Feb-2011 08:59:47 GMT; path=/
Connection: close
Transfer-Encoding: chunked
"data here"
The data is transmitted in "chunks", i.e. a block of bytes that's preceded by its length. To quote Wikipedia's example:
HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked
25
This is the data in the first chunk
1C
and this is the second one
3
con
8
sequence
0
The only relevant header here is Transfer-Encoding: chunked
. You'll see that there is a hex number on the first line. That tells you how many bytes to expect in the following chunk - 25 in hex is 37 in decimal, and sure enough, there's a linebreak after 37 chars, followed by another hex number with the byte count of the following chunk, and so on until the end - the last chunk size MUST be 0, signifying end of data. (The chunk sizes are not part of the content). The decoded message would be this:
This is the data in the first chunk
and this is the second one
consequence
Edit: It seems that there is an existing function in PECL for this, http_chunked_decode() - and there's a pure PHP implementation on that page, too - just pass it the chunked data, and it will try to "unchunk" it.
精彩评论