来自 php 的 echo“按情况进行”
在脚本结束之前打印内容时,从 php 脚本打印结果的方法是什么?我尝试使用输出缓冲区,将 sleep() 放在 echo 之间进行测试,但结果始终在脚本执行后显示。这也是浏览器端的事情吗?
what was the way to print results from a php script while it's printing stuff before the script ends? i tried to play with output buffer, putting sleep() between echos to test but the result is always showed after the script executes. Is it a browser-side thing too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 PHP 脚本中,您所能做的就是调用 ob_flush 来尝试将所有当前输出刷新到用户浏览器,但它实际上还取决于许多其他事情。
HTTP 服务器有自己的缓冲,浏览器可能不会立即渲染它收到的每个数据包。它就像一个长长的不同级别的缓冲区管道,在您在浏览器中看到任何内容之前都必须刷新所有缓冲区,并且 PHP 输出缓冲区位于最高级别。
All you could do in your PHP script to try to flush all the current output to the user's browser is a call to
ob_flush
, but it actually depends on many other things as well.The HTTP server has its own buffering, and the browser may not instantly render every packet it receives. It's like a long pipeline of buffers at different levels that all have to be flushed before you see anything in the browser, and the PHP output buffer is at the highest level.
是的,你可以这样做
yes you can do that this way
PHP 是服务器端。如果您正在制作网页,那么在脚本结束并传输后,结果将始终显示在客户端上。
如果您在自己的计算机上运行脚本,那么我听说在执行过程中打印一个,在脚本完成后打印另一个。尝试在打印和回显之间切换,看看结果如何。
PHP is server side. If you are making a web page, then the results will ALWAYS be shown on the client after the script ends and has been transmitted.
If you are running the script on your own computer, then I heard somewhere that one prints during execution and the other after the script is done. Try switching between print and echo and see how your results go.
有 2 种解决方案:
1) 停用 php.ini 中的 output_buffering
2) 当使用循环时,请使用以下示例:
There are 2 solutions:
1) Deactivate the output_buffering in php.ini
2) When using loops use this for example:
PHP 一次性加载一个页面然后显示它。使用
flush()
在脚本加载时显示输出。PHP loads a page all at once then displays it. Use
flush()
to show output as the script loads.好问题..当我想做类似的事情(比如登录操作)时,我只使用 AJAX。我知道这可能不是你想要的,但听我说完。到目前为止,我也遇到过这个问题 4 次,并且我使用了 AJAX,因此我能够放置一个预加载器(这真的很酷而且很有帮助) :))
“使用 ajax”是指如果您有 4 个操作要显示,则执行 4 个 ajax 请求。我知道这不是最优雅的解决方案(因为您做了很多额外的事情),但它是一个很好的设计解决方案。
Nice question.. when I want to do something like that (like loggin actions) I just use AJAX. And I know it's not probably what you wanted but hear me out.. I have had this problem as well 4 times so far and I've used AJAX and because of that I was able to put a preloader (which is really cool and helpful :))
By "use ajax" I mean if you have 4 actions to show up do 4 ajax requests. I know it's not the most elegant solution (as you do a lot of extra stuff) but it is a good design-wise solution.