Search code examples
phpflush

PHP - ob_flush - clean old text and print new text in loop


I'm trying to create a script which will be print text in for loop. Here is my script:

<?php

for($i = 0; $i < 10; $i ++) {
    sleep(3);
    echo $i;
    flush();
    ob_flush();
}

?>

But this script sum every loop text. I want to clear buffer every loop and then print new text. Is it possible?

Thanks.


Solution

  • You could update the body using JavaScript, by example :

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Update</title>
    </head>
    <body>
    <?php
    for($i = 0; $i < 10; $i ++) {
        sleep(3); // usleep(300000);
        echo '<script>document.body.innerHTML="'.$i.'";</script>';
        flush();
        ob_flush();
    }
    ?></body>
    </html>