当前位置:首页 > PHP教程 > php应用 > 列表

关于PHP 如何用 curl 读取 HTTP chunked 数据

发布:smiling 来源: PHP粉丝网  添加日期:2021-07-11 20:06:25 浏览: 评论:0 

通过本文给大家介绍php用curl读取http chunked数据的方法,本文介绍的非常详细,具有参考借鉴价值,感兴趣的朋友一起学习吧。

对于 Web 服务器返回的 HTTP chunked 数据, 我们可能希望在每一个 chunk 返回时得到回调, 而不是所有的响应返回后再回调. 例如, 当服务器是 icomet 的时候.

在 PHP 中使用 curl 代码如下:

  1. <?php  
  2. $url = "http://127.0.0.1:8100/stream"
  3. $ch = curl_init($url); 
  4. curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'myfunc'); 
  5. $result = curl_exec($ch); 
  6. curl_close($ch); 
  7. function myfunc($ch$data){ 
  8. $bytes = strlen($data); 
  9. // 处理 data 
  10. return $bytes

但是, 这里有一个问题. 对于一个 chunk, 回调函数可能会被调用多次, 每一次大概是 16k 的数据. 这显然不是我们希望得到的. 因为 icomet 的一个 chunk 是以 "\n" 结尾, 所以回调函数可以做一下缓冲.

  1. function myfunc($ch$data){ 
  2. $bytes = strlen($data); 
  3. static $buf = ''
  4. $buf .= $data
  5. while(1){ 
  6. $pos = strpos($buf"\n"); 
  7. if($pos === false){ 
  8. break
  9. $data = substr($buf, 0, $pos+1); 
  10. $buf = substr($buf$pos+1); 
  11. // 处理 data 

下面给大家介绍下chunked php使用fsockopen读取分段数据(transfer-encoding: chunked)

使用fsockopen读取数据时遇到了一个神奇的问题,具体情况如下:

读取地址:http://blog.maxthon.cn/?feed=rss2

读取代码:

  1. <?php 
  2. $fp = fsockopen("blog.maxthon.cn", 80, $errno$errstr, 30); 
  3. if (!$fp) { 
  4. echo "$errstr ($errno)<br />\n"
  5. else { 
  6. $out = "GET /?feed=rss2 HTTP/1.1\r\n"
  7. $out .= "Host: blog.maxthon.cn\r\n"
  8. $out .= "Connection: Close\r\n\r\n"
  9. fwrite($fp$out); 
  10. while (!feof($fp)) { 
  11. echo fgets($fp, 128); 
  12. fclose($fp); 
  13. ?> 

返回http内容:

  1. Date: Mon, 29 Mar 2010 10:16:13 GMT 
  2. Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8b PHP/5.2.6 
  3. X-Powered-By: PHP/5.2.6 
  4. X-Pingback: http://blog.maxthon.cn/xmlrpc.php 
  5. Last-Modified: Wed, 03 Mar 2010 03:13:41 GMT 
  6. ETag: "8f16b619f32188bde3bc008a60c2cc11" 
  7. Keep-Alive: timeout=15, max=120 
  8. Connection: Keep-Alive 
  9. Transfer-Encoding: chunked 
  10. Content-Type: text/xml; charset=UTF-8 
  11. 22de 
  12. <?xml version="1.0" encoding="UTF-8"?> 
  13. <rss version="2.0" 
  14. <description><![CDATA[2009年12月31日 
  15. 1711 
  16. ....... 
  17. 1fe8 
  18. ]]></description> 
  19. <content:encoded><![CDATA[<p>2009年12月31日<br /> 
  20. 1711</p> 

请注意上面那些标红的4个字符,它们每隔一段数据就会出现一次,但是用其他的方法如curl,file_get_contents等取回的数据则没有这些玩意。换成其他的网站来抓取,也只是少数的网站会出现这种情况,多方搜索无解后,我无意中看到了上面返回头中有这么一个声明:Transfer-Encoding: chunked,而常见的Content-lenght字段没有了。这个声明的大致的意思是传输编码为分段方式。

在Google上搜索该关键词,在维基百科上找到对这个声明的解释(由于没有中文版,我只能自己按照意思翻译):

Chunked Transfer Encoding is a mechanism that allows HTTP messages to be split in several parts. This can be applied to both HTTP requests (from client to server) and HTTP responses (from server to client)

分块传输编码是一种机制,允许将HTTP消息分成几个部分传输。同时适用于HTTP请求(从客户端到服务器)和 HTTP响应(从服务器到客户端)

For example, let us consider the way in which an HTTP server may transmit data to a client application (usually a web browser). Normally, data delivered in HTTP responses is sent in one piece, whose length is indicated by the Content-Length header field. The length of the data is important, because the client needs to know where the response ends and any following response starts. With chunked encoding, however, the data is broken up into a series of blocks of data and transmitted in one or more "chunks" so that a server may start sending data before it knows the final size of the content that it's sending. Often, the size of these blocks is the same, but this is not always the case.

例如,让我们考虑HTTP服务器可将数据传输到客户端应用程序(通常是一个网络浏览器)使用哪些方式。通常情况下,在HTTP响应数据是按照一整块发送给客户端的,数据的长度是由Content - Length头域表示。数据的长度很重要,因为客户需要知道在哪里响应结束和后面的响应何时启动。而使用Chunked编码方式,不管怎样,数据都会分割成一系列的数据块和一个或多个转发的“块”,因此服务器在知道内容的长度之前,就可以开始发送数据后。通常情况下,这些数据块的大小是一样的,但也并不是绝对的。

大概意思了解后,我们来看例子:

Chunked编码使用若干个Chunk串连而成,由一个标明长度为0的chunk标示结束。每个Chunk分为头部和正文两部分,头部内容指定下一段正文的字符总数(十六进制的数字)和数量单位(一般不写),正文部分就是指定长度的实际内容,两部分之间用回车换行(CRLF)隔开。在最后一个长度为0的Chunk中的内容是称为footer的内容,是一些附加的Header信息(通常可以直接忽略)。具体的Chunk编码格式如下:

编过码的响应内容:

HTTP/1.1 200 OK

Content-Type: text/plain

Transfer-Encoding: chunked

25

这是第一段数据

1A

然后这是第二段数据

0

解码的数据:

这是第一段内容,然后这是第二段数据

情况搞清楚了,那么我们怎么来解码这个编码后的数据呢?

在php官方手册fsockopen函数下面的评论中,已经有很多人提出了解决方法

方法1.

  1. <?php 
  2. function unchunk($result) { 
  3. return preg_replace_callback( 
  4. '/(?:(?:\r\n|\n)|^)([0-9A-F]+)(?:\r\n|\n){1,2}(.*?)'
  5. '((?:\r\n|\n)(?:[0-9A-F]+(?:\r\n|\n))|$)/si'
  6. create_function( 
  7. '$matches'
  8. 'return hexdec($matches[1]) == strlen($matches[2]) ? $matches[2] : $matches[0];' 
  9. ), 
  10. $result 
  11. ); 

方法二.

  1. function unchunkHttp11($data) { 
  2. $fp = 0; 
  3. $outData = ""
  4. while ($fp < strlen($data)) { 
  5. $rawnum = substr($data$fpstrpos(substr($data$fp), "\r\n") + 2); 
  6. $num = hexdec(trim($rawnum)); 
  7. $fp += strlen($rawnum); 
  8. $chunk = substr($data$fp$num); 
  9. $outData .= $chunk
  10. $fp += strlen($chunk); 
  11. return $outData

注意:这两个函数的参数都是返回的http原始数据(包括头)

Tags: curl HTTP chunked

分享到: