Skip to content

Why progress bar appear after the for loop completely processed

An answer to this question on Stack Overflow.

Question

Following is my script in which I put the progress bar to tell the user about the progress of sheets data being processed the problem is that the progress bar appears after the whole process of saving xls to csv being done kindly let me know how can i modify the following so that progress bar appears correctly right on when the current sheet is on process. Thanks,

$excel = new Spreadsheet_Excel_Reader();
    $excel->setOutputEncoding('UTF-16');
    $excel->read('Student2.xls');
	$x=1;
    $sep = ",";
    
   $nbSheets = count($excel->sheets);
  echo $x." -  ".$nbSheets;
  
  $total = $nbSheets - 1;
  
for($i = 0; $i < $nbSheets; $i++) {
	
	
    // Calculate the percentation
    $percent = intval($i/$total * 100)."%";
 
    // Javascript for updating the progress bar and information
    echo '<script language="javascript">
    document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\">&nbsp;</div>";
    document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
    </script>';
 
    // This is for the buffer achieve the minimum size in order to flush data
    echo str_repeat(' ',1024*64);
 
    // Send output to browser immediately
    flush();
	//sleep(1);
   ob_start();
    while($x<=$excel->sheets[$i]['numRows']) {
        $y=1;
        $row="";
        while($y<=$excel->sheets[$i]['numCols']) {
            $cell = isset($excel->sheets[$i]['cells'][$x][$y]) ? $excel->sheets[$i]['cells'][$x][$y] : '';
            $row.=($row=="")?"\"".$cell."\"":"".$sep."\"".$cell."\"";
            $y++;
        } 
        echo $row."\n"; 
        $x++;
    }
	$x = 1; $y = 1;
	$fp = fopen("data.csv",'a');
    fwrite($fp,ob_get_contents());
    fclose($fp);
    ob_end_clean();
	
}
    
echo "CSV file created successfully";
// Tell user that the process is completed
echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';

Answer

You'll need to use AJAX, or something client-server communications framework, to make this happen.

You could try looking at this example code (download the code via the link near the bottom of the article).

This SO question and this question seem to address a similar issue.

Much as I hate to say it, searching "ajax php progressbar" will likely bring up a host of examples.