在foreach循环中运行函数时进度条

I have a foreach loop that calls a function to set values to an array. Sometimes it takes hours to complete depending on how many times it has to run thru the function to complete.

What I would like to have is a progress bar or at least a 1/1000 completed type progress indicator.

Is this possible? If so how could I implement this into my code? Would it be in the function or in the foreach loop? Been researching and found some examples using for and $i++ but I am not really sure how to implement that since I am already using a foreach loop.

Thanks much.

 function scrape_amazon($links) {
 //my code runs here to set all values in $ret array.
 }


 foreach($links as $link) {
$ret = scrape_amazon($link);
 }

PHP probably isn't really the right tool for this task, however what you could do is:

  • Launch the slow code as a background process, and output progress to a file.
  • Have a PHP script that polls that file for progress information (either by page refresh or AJAX)

Launching the background process can be done in several ways, including:

  • Launch via cron every 60 seconds, and poll for new jobs spooled in some readable area
  • Launch via a fork/exec mechanism from a web page
  • Launch as a daemon at system startup

It will take some effort to avoid problems with multiple executions and/or overlap.

I use this, which well, not an ajax, do only flushing, but not so ugly.

I place an image

<img src='progress.gif' height=18 width=0 name=probar>

Then set on every event done on server a echo a line, then flush:

echo "<script language='JavaScript'>
document.probar.width=".(($sys["probar_width"]/$task_all)*$task_i).";
</script>
";
flush();

If your server (eg. apache) use caching (eg. gzip is enabled) it won't work well.