如何从php实时获取输出? [英] How to get realtime output from php as it happens?

查看:137
本文介绍了如何从php实时获取输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实时获取php的实时输出?而不是将所有内容存储在内存/缓冲区中并一次将所有内容回显到浏览器中?



如果我创建了realtime-echo.php

 <?php 
for($ i = 0; $ i< 10; $ i ++)
{
echo $ i ;
sleep(1);
}

并从Internet浏览器访问它,在9-10秒后给出以下输出。

  0123456789 

但是我希望输出的是,当我从浏览器访问php文件时,应该给出



0



然后等待1秒钟,然后在 0
之后添加 1,然后等待1秒钟,然后在 1
之后添加 2,依此类推。 / p>

idk称为动画/实时。



如何实现?



我正在从事需要持续产出的项目,因此我可以随时关注正在发生的事情和进展情况。



谢谢

解决方案

使用 flush() 函数要显示当前输出。



一个简单的例子:

 <?php 
for($ i = 1; $ i< = 10; $ i ++)
{
echo’< p>’。 $ i。 ‘< / p>’;
flush();
sleep(1);
}
?>

如果使用输出缓冲,则还需要调用 ob_flush()



注意:某些版本的Microsoft Internet Explorer仅在收到256字节的输出后才开始显示页面,因此您可能需要在刷新之前发送额外的空格以使那些浏览器显示页面。



类似这样的东西:

 <?php 
echo str_repeat(,256);
flush();
?>

工作示例(没有 ob_start()函数):

 <?php 
echo str_repeat(,256);
for($ i = 1; $ i< = 10; $ i ++)
{
sleep(1);
echo‘< p>’。 $ i。 ‘< / p>’;
flush();
}
?>


How to get real-time output from php as it happens ? without storing all in memory/buffer and echoing all at once to the browser ?

if i create a realtime-echo.php

<?php
for($i = 0; $i < 10; $i++)
{
echo $i;
sleep(1);
}

and access it from Internet browser it gives following output , after 9-10 seconds.

0123456789

but what i am willing the output to be is, when i access the php file from my browser it should give

0

then wait 1 second then add "1" after the "0" then wait 1 second then add "2" after the "1" and so on.

idk what its called like animation/real-time .

How do achieve this ?

I am working on the project where i need the constant output as it happens so i can keep eye on whats happening and where its going.

Thanks

解决方案

Use flush() function when you want the current output to be displayed.

A quick example:

<?php
for ($i = 1; $i <= 10; $i++)
{
   echo '<p>' . $i . '</p>';
   flush();
   sleep(1);
}
?>

If you are using output buffering, you also need to call ob_flush()

Note: Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.

Something like this:

<?php
echo str_repeat(" ", 256); 
flush();
?>

Working example (without ob_start() function):

<?php
echo str_repeat(" ", 256);
for ($i = 1; $i <= 10; $i++)
{
    sleep(1);
    echo '<p>' . $i . '</p>';
    flush();
}
?>

这篇关于如何从php实时获取输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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