Search code examples
phpcsvwhile-loopsleepfopen

How to echo something in a while loop with sleep()?


I've got a while loop to read a csv file with customer data (Name, Email, Website). i use to echo each row each second. so i do a while loop with sleep(1) and alot of hope, but the browser is waitong untill its fully loeaded. i know, thats how php works and maybe its easy with javacript, but i've got really no glue about javascript. Even flush() technics dont works. Maybe a problem on my host? i use one.com

i tried already just the sleep() within the loop. - loading untill finished i tried already flush functions - same same

$handle = fopen ("csv.csv","r");
$csv = array();

while ( ($data = fgetcsv ($handle, 1000, "\t")) !== FALSE ) {
    $csv[] = $data;
    echo "Name=".$data[0]."<br>Email=".$data[1]."<br>Website=".$data[2];
    sleep(1);
}
fclose ($handle);

Solution

  • You can use both, php and javascript to perform this operation.

    Step 1: Javascript will do a single ajax call on php to get the csv data into form of json.

    Step 2: PHP will read the csv file, store data into an array and return the json encoded data back to javascript.

    Step 3: Loop through the backend data in javascript using setInterval function like this:

    var data = /* json data from ajax call */;
    
    var i=0, html='';
    var loop = setInterval(function(){
        // Perform the operation here, which will print some data at interval of 1 second
        if(i==data.length) {
            clearInterval(loop);
        }
    }, 1000);