Search code examples
phpxmlhttprequest

PHP Clear buffer during for loop


test.html

<html>
<head>
    <title>Ajax Streaming Test</title>
</head>
<body>
<center><a href="#" id="test">Test Ajax Streaming</a></center>
<script type="text/javascript">
    document.getElementById('test').onclick = function () {
        xhr = new XMLHttpRequest();
        xhr.open("GET", "test1.php", true);
        xhr.onprogress = function (e) {
            console.log(e.currentTarget.responseText);
        }
        //xhr.onreadystatechange = function () {
        //    if (xhr.readyState == 4) {
        //        console.log("Complete = " + xhr.responseText);
        //    }
        //}
        xhr.send();
    };
</script>
</body>
</html>

test1.php

for ($i = 1; $i <= 3; $i++):
    sleep(1);
    echo "$i\n";
    ob_flush();
    flush();
endfor;

after click on link in test.html page, console show this results :

  • 1

  • 1
    2

  • 1
    2
    3

What is the method to clean buffer before echo $i to get result like this :

  • 1
  • 2
  • 3

Thank you


Solution

  • You can use ob_clean(); It will clear the whole output buffer:

    for ($i = 1; $i <= 3; $i++):
        sleep(1);
        ob_clean();
        echo "$i\n";
        ob_flush();
        flush();
    
    endfor;