Using flush() replace last line rather than make n

2019-04-15 18:46发布

问题:

Lets say my php code is similar to below. . .

$range = range(0, 5);
foreach ($range as $times) {
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<1; $i++){
echo "<br>example ".$times;
echo str_pad('',4096)."\n";   
ob_flush();
flush();
sleep(1.2);
}
ob_end_flush();
}

What it displays is. . .

example1
example2
example3
example4
example5

It waits a short period of time before showing the next line, I don't want to display all five at once, I want to replace example1 with the next one and so on for all five is this possible in php? any answers welcome

回答1:

You Would need to use javascript to replace the element already on the page:

<p id="ob">1</p>
<?php
$range = range(0, 5);
foreach ($range as $times) {
    if (ob_get_level() == 0) ob_start();
    for ($i = 0; $i<1; $i++){
        echo "<script>document.getElementById('ob').innerHTML ='example$times';</script>";
        echo str_pad('',4096)."\n";
        ob_flush();
        flush();
        sleep(1.2);
    }
    ob_end_flush();
}
?>

Or a much better way would be to use AJAX to poll the server for the next value.

<?php
if(isset($_GET['poll'])){
    echo $_GET['poll']+1;
    die;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var value = 0;
function poll(){
    setTimeout(function(){
        $.ajax({ url: "./test.php?poll="+value,cache: false,
        success: function(data){
            value = data;
            $("#ob").html('example'+value);
            //Next poll
            poll();
        }});
    }, 1200);
}

$(document).ready(function(){
    poll();
});
</script>
<p id="ob">example0</p>


回答2:

Assuming that you are outputting html, you should do that on the client side in javascript.

The php alternative would be to show one line and have the page reload to show the next one. Needlessly complex and a waste of resources.

Note that php cannot modify html that is already sent to the browser.