PHP shows foreach output to screen, for each element

One thing I noticed with php is that nothing is displayed on the screen until the script stops working. For the project I'm working on, I upload a list of more than 100 elements and execute an HTTP request for each element and upon completion it shows a page with the status of each element, failure success, etc.

What I want to know is there a way to output the results of each foreach loop when they happen? Thus, the user watching the screen sees the magic occurring on one line at a time or after 5 lines.

I only ever saw this with requests like Ajax, is that what I should do instead, maybe? Can someone point me to a php function that does this or is it impossible?

+3
source share
4 answers

It might be better to save all script output in a buffer, and then flush the buffer if necessary.

For example:

<?php

if (ob_get_level() == 0) ob_start();

$test = Array('one','two','three','four');
foreach ($test as $key=>$val)
{
    echo $test;
    ob_flush();
    flush();
}

ob_end_flush();

?>

Make sure mod_gzip is disabled!

+6
source

flush()should do this, or you can see all output buffering functions

+7
source

flush()

+2

flush(); @ob_flush();

.

+1

Source: https://habr.com/ru/post/1713865/


All Articles