Home > Backend Development > PHP Tutorial > PHP uses curl to read HTTP chunked data

PHP uses curl to read HTTP chunked data

WBOY
Release: 2016-07-29 09:00:06
Original
1563 people have browsed it

For the HTTP chunked data returned by the Web server, we may want to get a callback when each chunk returns, instead of calling back after all responses are returned. For example, when the server is icomet.

The curl code used in PHP is as follows :

<?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;
}
Copy after login

But, there is a problem here. For a chunk, the callback function may be called multiple times, each time about 16k of data. This is obviously not what we want. Because a chunk of icomet starts with "n" At the end, so the callback function can be buffered.

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
    }
}
Copy after login

Qianaa-customized IT education platform, one-on-one service by talented people, answer all your questions, development and programming social headlines official website: www.wenaaa.com Download the Qianaa APP, Participate in the official reward and earn 100 yuan in cash.

QQ group 290551701 gathers many Internet elites, technical directors, architects, and project managers! Open source technology research welcomes industry insiders, experts and novices who are interested in working in the IT industry!

The above introduces PHP to use curl to read HTTP chunked data, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template