0

I have this code snippet:

foreach ($data as $key => $value) {
  $result = $this->_restFetch($value);
  $mode[$key] = $result[0]->extract;
}

Just some basic code that runs in a for loop sending a request to some API. It takes time to finish the script, so I'd like to output some text to the user while the script is executing, something like bellow:

foreach ($data as $key => $value) {
   print "Started importing $value \r\n";
   $result = $this->_restFetch($value);
   $mode[$key] = $result[0]->extract;
   print "Finished importing $value \r\n"; 
}

I've tried various approached with ob_ commands but none of them worked. Any ideas?

lordZ3d
  • 540
  • 6
  • 20

1 Answers1

2

After each print line, you have to put flush(), so the content would be printed out immediately. Good to keep in mind that the browser needs to have some minimum data to display (about .5Kb). I have put both ob_flush() and flush() because in that way you are sure that output will be shown. More on flush() and ob_flush() you can see in this topic PHP buffer ob_flush() vs. flush().

usleep function you can use to delay execution of code for debugging purposes.

foreach ($data as $key => $value) {
   print "Started importing $value \r\n";
   usleep(3600); // if you are debugging, otherwise just comment this part
   ob_flush();
   flush();

   $result = $this->_restFetch($value);
   $mode[$key] = $result[0]->extract;
   print "Finished importing $value \r\n"; 
   usleep(3600); // if you are debugging, otherwise just comment this part
   ob_flush();
   flush();
}
Budimir Skrtic
  • 419
  • 3
  • 12
  • Yup that's it, thanks. Problem was i had ob_start at the start of my script, after removing that, and applying your solution the printing works. – lordZ3d Apr 01 '19 at 14:26