PHP 在页面加载时回显内容 [英] PHP echo-ing content as page loads
问题描述
所以我正在尝试使用 PHP/Apache.假设我有这个代码.
DIV 1<?php sleep(2);?><div>DIV 2</div><?php sleep(2);?><div>DIV 3</div><?php sleep(2);?><div>DIV 4</div><?php sleep(2);?>
出于某种原因,在我的本地 apache 网络服务器上,所有数据都立即出现在浏览器中,在执行完所有 4 个 sleep() 之后(8 秒).
但是,如果我在主机的服务器上运行它,数据会实时回显到浏览器.如... div1 出现,2 秒后 div 2 出现等
这是为什么?这是 Apache 中的某些设置吗?
不,这可能是 php 中的设置.
在您的本地服务器中,您的 php.ini 文件中启用了 output_buffering.
您可以通过设置禁用它:
output_buffering = off
要确保每次使用类似 echo 的语句时都将内容发送到浏览器,请添加:
implicit_flush = on
您还可以通过给 output_buffering 一个值来设置缓冲区大小.
output_buffering = 4096
此处的缓冲区大小为 4KB.
输出缓冲告诉 php 将所有要发送到浏览器的数据保存在内存中,直到它在您的代码中遇到 flush() 指令,缓冲区恰好已满,或者脚本结束.
这里是来自 php.net 的输出缓冲区的完整参考:php 输出缓冲区
So I'm doing some experimenting with PHP/Apache. Let's say I have this code.
<div>DIV 1</div>
<?php sleep(2); ?>
<div>DIV 2</div>
<?php sleep(2); ?>
<div>DIV 3</div>
<?php sleep(2); ?>
<div>DIV 4</div>
<?php sleep(2); ?>
For some reason on my local apache webserver all the data appears in the browser at once, after all 4 sleep()s have been executed (8 seconds).
However if I run it on my host's server, the data is echo-ed to the browser in real time. As in... div1 appears, after 2 seconds div 2 appears etc.
Why is that? Is this some setting in Apache?
No it may be a setting in php.
In you local server, output_buffering is enabled in your php.ini file.
You can disable it by setting :
output_buffering = off
To Ensure that the content is sent to the browser each time a echo-like statement is used, add :
implicit_flush = on
You also can set the buffer size by giving output_buffering a value.
output_buffering = 4096
here the buffer size would be 4KB.
Output buffering tells php to keep in memory all data to be sent to the browser until it encouters a flush() instruction in your code, the buffer happens to be full, or it is the end of the script.
Here is the full reference for output buffer from php.net : php output buffer
这篇关于PHP 在页面加载时回显内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!