2016-02-25

PHP 用 curl 读取 HTTP chunked 数据

Views: 20191 | Add Comments

对于 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
    }
}

Related posts:

  1. iOS 正确接收 HTTP chunked 数据的方法
  2. HTTP POST using PHP cURL
  3. 写自己的 http_build_query
  4. 史上最强大的PHP MySQL操作类
  5. PHP 解码 C 字符串
Posted by ideawu at 2016-02-25 16:44:11

Leave a Comment