如何让PHP生成Chunked响应 [英] How to make PHP generate Chunked response

查看:140
本文介绍了如何让PHP生成Chunked响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用谷歌搜索了这个问题,但没有答案。

I googled for this problem but there is no answer for it.

我希望我的PHP脚本在chunked中生成HTTP响应( http://en.wikipedia.org/wiki/Chunked_transfer_encoding )。怎么做?

I want my PHP script to generate HTTP response in chunked( http://en.wikipedia.org/wiki/Chunked_transfer_encoding). How to do it?

更新:
我想通了。我必须指定传输编码标头并将其刷新。

Update: I figured it out. I have to specify Transfer-encoding header and flush it.

header("Transfer-encoding: chunked");
flush(); 

需要冲洗。否则,将生成Content-Length标头。

The flush is necessary. Otherwise, Content-Length header will be generated.

而且,我必须自己制作块。有了辅助函数,它并不难。

And, I have to make chunks by myself. With a helper function, it is not hard.

function dump_chunk($chunk)
{
    echo sprintf("%x\r\n", strlen($chunk));
    echo $chunk;
    echo "\r\n";
}


推荐答案

自16.02起的工作样本。 2013

Working sample as of 16.02.2013

<?php

function dump_chunk($chunk) {
    //echo sprintf("%x\r\n", strlen($chunk));
    echo sprintf("\r\n");
    echo $chunk;
    echo "\r\n";
}

ob_start();
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Title</title>
    </head>
    <body>
        <?php
        ob_end_flush();
        flush();
        ob_flush();
        for ($i = 0; $i < 5; $i++) {
            sleep(1);
            dump_chunk('Sending data chunk ' . ($i + 1) . ' of 1000 <br />');
            flush();
            ob_flush();
        }
        sleep(1); // needed for last animation
        ?>
    </body>
</html>

这篇关于如何让PHP生成Chunked响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆