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; }
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 } }
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.