PHP:在sleep()之前和之后输出数据? [英] PHP: Output data before and after sleep()?

查看:268
本文介绍了PHP:在sleep()之前和之后输出数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这纯粹是为了学习更多有关输出缓冲的知识,仅此而已.我想做的是将字符串回显到浏览器,睡眠10秒钟,然后回显其他内容.通常,浏览器会等待整整10秒钟,然后发布整个结果,我该如何停止呢?一个例子:

This is purely for learning more about output buffering and nothing more. What I wish to do is echo a string to the browser, sleep 10 seconds, and then echo something else. Normally the browser would wait the full 10 seconds and then post the whole result, how I would I stop that? An example:

ob_start();
echo "one";
sleep(10);
echo "two";

推荐答案

faileN的回答在理论上是正确的.如果没有ob_flush(),数据将留在PHP的缓冲区中,直到请求结束时隐式刷新缓冲区后,数据才到达浏览器.

faileN's answer is correct in theory. Without the ob_flush() the data would stay in PHP's buffer and not arrive at the browser until the buffer is implicitly flushed at the end of the request.

它仍然不起作用的原因是因为浏览器还包含缓冲区.现在,数据已正确发送出去,但是浏览器在获得一个"之后等待,然后才真正开始渲染.否则,如果连接速度较慢,则页面渲染会非常非常慢.

The reason why it still doesn't work is because the browsers also contain buffers. The data is now sent out correctly, but the browser waits after getting "one" before it actually kicks off rendering. Otherwise, with slow connections, page rendering would be really, really slow.

解决方法(以说明它是否正常工作)当然是一次发送大量数据(也许是一些巨大的html注释或其他内容),或者在命令行上使用诸如curl的工具.

The workaround (to illustrate that it's working correctly) is, of course, to send a lot of data at once (maybe some huge html comment or something) or to use a tool like curl on the command line.

如果您想将此发送/睡眠周期用于客户端上的某些状态更新UI,则必须找到另一种方式(例如长轮询和AJAX)

If you want to use this sending/sleeping cycle for some status update UI on the client, you'd have to find another way (like long-polling and AJAX)

这篇关于PHP:在sleep()之前和之后输出数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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