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?

2
  • what is $value? array? string? Commented Apr 1, 2019 at 13:31
  • Try calling flush() after every line to be printed. Commented Apr 1, 2019 at 13:33

1 Answer 1

3

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(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.