PHP showing output of foreach to screen, for each item
Asked Answered
A

5

5

One thing I have noticed with php, is that nothing is output to the screen until the script has stopped working. For the project I am working on I feed in a list of over 100 items and it performs a HTTP request for each item and when finished, shows a page with the status of each item, success failure etc.

What I want to know is if there is a way to output the results of each 'foreach' loop as they happen? So the user watching the screen sees the magic happening one line at a time or after say 5 lines.

I have only ever seen this done with Ajax type requests, is that what I should be looking to do instead maybe? Can anyone point me to a php function that does this or is it not possible?

Abagael answered 29/7, 2009 at 15:28 Comment(0)
I
10

It may be better to store all script output in a buffer then flush the buffer when required.

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 you have mod_gzip disabled!

Izawa answered 29/7, 2009 at 15:54 Comment(0)
R
7

flush() should do it, or you can look at all the output buffering functions

Reitman answered 29/7, 2009 at 15:32 Comment(0)
I
2

Use the flush() command

Incorporate answered 29/7, 2009 at 15:31 Comment(0)
G
1

I use

flush(); @ob_flush();

after the output.

Glint answered 29/7, 2009 at 16:1 Comment(0)
D
-1

Here is a working solution:

set_time_limit(0);
ob_implicit_flush(true);ob_end_flush(); 
@ob_flush();
echo '<div class="row b p-0 my-2 mail_progress" >';
foreach(range(1,100) as $k=>$v ){
    @ob_flush();
    echo '<b>|</b>';
    usleep(45000);
}
echo '</div>';
Dissepiment answered 8/8, 2023 at 14:15 Comment(1)
Please add some explanation to your answer such that others can learn from it. What does it add to the other existing answers on this question?Inclining

© 2022 - 2024 — McMap. All rights reserved.