对于 Web 服务器返回的 HTTP chunked 数据, 我们可能希望在每一个 chunk 返回时得到回调, 而不是所有的响应返回后再回调. 例如, 当服务器是 icomet 的时候.
在 PHP 中使用 curl 代码如下:
<?php $url = "http://127.0.0.1:8100/stream"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'myfunc'); $result = curl_exec($ch); curl_close($ch); function myfunc($ch, $data){ $bytes = strlen($data); // 处理 data return $bytes; }
但是, 这里有一个问题. 对于一个 chunk, 回调函数可能会被调用多次, 每一次大概是 16k 的数据. 这显然不是我们希望得到的. 因为 icomet 的一个 chunk 是以 "\n" 结尾, 所以回调函数可以做一下缓冲.
function myfunc($ch, $data){ $bytes = strlen($data); static $buf = ''; $buf .= $data; while(1){ $pos = strpos($buf, "\n"); if($pos === false){ break; } $data = substr($buf, 0, $pos+1); $buf = substr($buf, $pos+1); // 处理 data } }
下面给大家介绍下chunked php使用fsockopen读取分段数据(transfer-encoding: chunked)
使用fsockopen读取数据时遇到了一个神奇的问题,具体情况如下:
读取地址:
读取代码:
<?php $fp = fsockopen("blog.maxthon.cn", 80, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { $out = "GET /?feed=rss2 HTTP/1.1\r\n"; $out .= "Host: blog.maxthon.cn\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) { echo fgets($fp, 128); } fclose($fp); } ?>
返回http内容:
Date: Mon, 29 Mar 2010 10:16:13 GMT Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8b PHP/5.2.6 X-Powered-By: PHP/5.2.6 X-Pingback: Last-Modified: Wed, 03 Mar 2010 03:13:41 GMT ETag: "8f16b619f32188bde3bc008a60c2cc11" Keep-Alive: timeout=15, max=120 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/xml; charset=UTF-8 22de <?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" <description><![CDATA[2009年12月31日 1711 ....... 1fe8 ]]></description> <content:encoded><