0

I have to output results while PHP script is running:

ob_implicit_flush(true);
ob_start();
for ($i=0; $i<5; $i++) {
    echo $i . ' - ';
    ob_end_flush();
    flush();
    sleep(1);
}

This is working but throwing warnings:

Notice: ob_end_flush(): failed to delete and flush buffer. No buffer to delete or flush in ...

How to fix that?

medk
  • 9,233
  • 18
  • 57
  • 79

3 Answers3

2

In the first loop you are ending the buffer. If you want to do that, you should start a new buffer in each loop.

ob_implicit_flush(true);
for ($i=0; $i<5; $i++) {
    ob_start();
    echo $i . ' - ';
    ob_end_flush();
    flush();
    sleep(1);
}

This is a neater way to use buffering. It is also more performant as you are only using 1 buffer. If you do not need to flush on each loop, you could skip the ob_flush within the loop and use ob_end_flush instead of ob_end_clean.

ob_implicit_flush(true);
ob_start();
for ($i=0; $i<5; $i++) {
    echo $i . ' - ';
    ob_flush();
    flush();
    sleep(1);
}
ob_end_clean();
Jim Wright
  • 5,905
  • 1
  • 15
  • 34
  • Thanks! but if starting a new buffer in each loop will have impact on performance, would it be better to just clean the first and re-use it? and how to do it? – medk Aug 09 '18 at 11:59
  • 1
    Why start the buffer multiple times? All he needs is `ob_flush()` – Blue Aug 09 '18 at 12:00
  • @FrankerZ I was editing the answer as you wrote your comment :P – Jim Wright Aug 09 '18 at 12:01
  • @JimWright this method is not working as it echoes everything at once and not after each loop – medk Aug 09 '18 at 12:05
  • 3
    @medk Have a look [here](https://stackoverflow.com/questions/6001628/php-flush-not-working-in-chrome). Output buffering can be a bit finicky in browsers. – Blue Aug 09 '18 at 12:08
1

ob_end_flush() will disable buffering, so future calls to this in your loop will fail. Simply use ob_flush(), which clears the buffer but maintains output buffering:

ob_implicit_flush(true);
ob_start();
for ($i=0; $i<5; $i++) {
    echo $i . ' - ';
    ob_flush();
    sleep(1);
}
ob_end_flush();
Blue
  • 22,608
  • 7
  • 62
  • 92
0

Ok, I fixed it like that:

ob_implicit_flush(true);
ob_start();
for ($i=0; $i<5; $i++) {
    echo $i . ' - ';
    flush();
    @ob_flush();
    @ob_end_clean();
    sleep(1);
}

It works now.

medk
  • 9,233
  • 18
  • 57
  • 79