技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> PHP --> PHP 用 curl 读取 HTTP chunked 数据

PHP 用 curl 读取 HTTP chunked 数据

浏览:1327次  出处信息

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

建议继续学习:

  1. php让服务器不返回chunked    (阅读:1964)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1