phpoutput-bufferingob-start

ob_get_clean, only works twice


Take this simple script:

ob_start();
$text = array();

echo 'first text';
$text[] = ob_get_clean();

echo 'second text';
$text[] = ob_get_clean();

echo 'third text';
$text[] = ob_get_clean();

echo 'fourth text';
$text[] = ob_get_clean();

print_r($text);

This outputs:

third textfourth textArray
(
    [0] => first text
    [1] => second text
    [2] => 
    [3] => 
)

But I would expect:

Array
(
    [0] => first text
    [1] => second text
    [2] => third text
    [3] => fourth text
)

PHPFiddle


Solution

  • To do this correctly you should be doing ob_start() after ob_get_clean() because ob_get_clean() gets the current buffer contents and delete the current output buffer.

    <?php
    ob_start();
    $text = array();
    
    echo 'first text';
    $text[] = ob_get_clean();
    ob_start();
    
    echo 'second text';
    $text[] = ob_get_clean();
    
    ob_start();
    
    echo 'third text';
    $text[] = ob_get_clean();
    
    ob_start();
    
    echo 'fourth text';
    $text[] = ob_get_clean();
    
    print_r($text);
    ?>