问题描述
我需要在从服务器到客户端的HTTP流上循环处理数百万条记录。因此,我取消了HTTP标头transfer-encoding = chunked的编写,并以这样的大小写了循环的每个元素:
$outputStreamResource = fopen('PHP://output','w');
header('Content-Type: application/octet-stream');
header('transfer-encoding: chunked');
// Write some content to $outputStreamResource before the loop
foreach ($recordStream as $record) {
// Output length of content in bytes
fwrite($outputStreamResource,sprintf('%x',mb_strlen($record,'8bit')));
fwrite($outputStreamResource,"\r\n");
fwrite($outputStreamResource,$record);
fwrite($outputStreamResource,"\r\n");
flush();
}
// Write some content to $outputStreamResource after the loop
// Send null byte to tell client,stream is finished
fwrite($outputStreamResource,'');
fclose($outputStreamResource);
这很好,可以产生所需的输出流。
但是,现在我需要对整个循环的结果进行base64编码(不是每个记录都单独记录)。我尝试使用PHP的内置stream filter base64-encode,如下所示:
$outputStreamResource = fopen('PHP://output','w');
header('Content-Type: application/octet-stream');
header('transfer-encoding: chunked');
// Write some content to $outputStreamResource before the loop
// Activate base64 for the entire record loop
$base64Filter = stream_filter_append($outputStreamResource,'convert.base64-encode');
foreach ($recordStream as $record) {
fwrite($outputStreamResource,$record);
flush();
}
// De-activate base64 and output the following content plainly
stream_filter_remove($base64Filter);
// Write some content to $outputStreamResource after the loop
// Send null byte to tell client,'');
fclose($outputStreamResource);
base64编码有效,但不是以带有块大小前缀的块格式进行的。任何想法如何实现这一目标?可以使用line-length
过滤器的参数convert.base64-encode
来手动分块输出。但是,这不会在每个结果块之前添加内容长度(以字节为单位)。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)