是否可以在不使用 JavaScript 的情况下立即在循环期间打印结果?
这是我希望每秒打印消息的代码示例。
set_time_limit(0);
foreach($array as $key => $value)
{
echo $value;
sleep(1);
}
我想知道是否可以在循环的每个步骤中立即输出结果,而无需等到它停止。
Here is example of code I'm expecting to print message each second.
set_time_limit(0);
foreach($array as $key => $value)
{
echo $value;
sleep(1);
}
I'm wondering is it possible to output results during each step in loop instantly, without waiting until it stops.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。
你可以使用 php 的刷新机制来做到这一点。
例如:
yes.
you can do it using php's flush mechanism.
for example:
这实际上是不可能的,因为网络服务器会缓存结果。当输出缓存填满并发送新的 http 数据包时,客户端可能会获取新数据,但这样做并不是一个好的做法,因为 php 脚本也会超时,因此这种方法的结果可能不明确。
编辑:您可以使用 php 的 ob_flush 使 php 清除缓存,如 <代码>ob_flush();。然而,这仍然存在脚本可能超时的问题,因此您不能长时间这样做。
更好的解决方案是定期进行 AJAX 调用或使用 WebSocket 保持与服务器的持久连接,以便在新数据出现时获取新数据。
编辑 2:对于 WebSockets,在这里发帖并不短。此外,它仅适用于 HTTP5,Chrome 8 支持它,可能 Firefox 4 和 Safari 5 也支持它。以下是通过 PHP 使用 Websockets 的教程: WebSockets with PHP< /a>
That's not really possible since the webserver caches the result. The client may get new data as the output cache fills up and sends a new http packet, but it's not good practice to do it like that, because php scripts also timeout, so the results of such an approach can be ambiguous.
Edit: you can make php clear the cache using php's ob_flush as in
ob_flush();
. However this still leaves the problem that the script might timeout, so you cannot keep doing this for a very long time.A much better solution would be to make AJAX calls periodically or use WebSockets to keep a persistent connection to the server, in order to get new data as it comes out.
Edit 2: For WebSockets, it's not that short to post here. Also, it only works in HTTP5, Chrome 8 supports it and probably Firefox 4 and Safari 5 as well. Here is a tutorial of using Websockets with PHP: WebSockets with PHP