Search code examples
phpoutput-buffering

PHP output buffering doesn't work!


ob_start();

for($i=1; $i<=10; $i++){
  echo 'FUU';
  $output = ob_get_contents();
}

echo $output;
ob_end_flush();  

So instead of one FUU I get 10! Why does my ob_start() not work?


Solution

  • I don't think you get what it's doing. Here's a walk through:

    $i = 1
    Output buffer = FUU
    ob_get_contents()/$output = FUU
    
    $i = 2
    Output buffer = FUUFUU
    ob_get_contents()/$output = FUUFUU
    
    $i = 3
    Output buffer = FUUFUUFUU
    ob_get_contents()/$output = FUUFUUFUU
    

    When you call ob_get_contents each iteration, it's getting everything that has been echoed.