PHP ob_start& flush - 在循环中打印和清理文本

时间:2017-04-21 19:31:55

标签: php flush ob-start

是否可以使用ob_start()& amp;在屏幕上打印文本? flush()并最后清理这个文本?

现在我有类似的东西:

['1', '23', '4', '5', '67']

当我执行这段代码时,我会得到类似的东西:

<?php
ob_start();

ob_end_flush(); flush(); ob_flush();
for($i = 0; $i<100; $i++)
{
    echo $i.'<br>';
    flush();
    ob_flush();
}

ob_end_flush();
?>

但我想要回声当前键并清理它们:

0
1
2
3
4
5
6
7
8
...

最后我想在屏幕上只有一个数字。在PHP中可以吗?

感谢。

3 个答案:

答案 0 :(得分:2)

根据OP的评论,我将假设OP在命令行上想要一个计时器,并假设<br>是为了传达换行符。

命令行上的一个计时器,每个刻度线清除该行,可以解释如下:

for( $i = 0; $i < 100; $i++ ) {
  /*
    the \r moves the cursor back to the start of the line
    the additional spaces are there to make sure 
    any additional digits are removed as well
    adjust the amount of spaces to the max amount of digits
    (which is actually only useful if the timer was counting down, in stead of counting up)
  */
  echo "$i  \r";
  // wait a second
  sleep( 1 );
}

ob_*函数在这里没用;在发送输出之前,它们仅仅是PHP的内部缓冲区。你无法清除已发出的内容。

如果您想完全清除屏幕,我建议您查看this question中的建议及相关问题。

但是,如果您通过Web服务器输出并在Web浏览器中查看结果,那么您就不走运了。您无法按照预期的方式清除已发送到Web浏览器的输出,因为Web是client <-> server体系结构。你必须understand this architecture and use something like AJAX, websockets, or perhaps long polling

答案 1 :(得分:2)

如果您需要在控制台中执行此操作,@ Decent Dabbler会显示最佳建议。 如果您需要在浏览器中执行此操作,则不需要PHP。你可以使用javascript。

function setCounter(value)
{
  document.getElementById('counter').innerText = value;
}

var counter = 0;
setInterval(
  function() {
    setCounter(++counter);
  },
  1000
);
<div id="counter"></div>

答案 2 :(得分:0)

解决方案就像电子商务和篮子和cookie一样,99次在客户端和服务器之间进行请求和回答。在$ $之后我必须退出,并再次请求cookie和$ i + 1。所有这些都是循环结束的。

也许这就是你想要的。屏幕上只有一个数字,最后一个,99。

<?php
    ob_start();

    for($i = 0; $i<100; $i++)
    {
        echo $i.'<br>';  
        //flush();
        //ob_flush();
        ob_clean();
        echo $i.'<br>';
    }

    ob_end_flush();
    ?>