Question

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

Was it helpful?

Solution

To do this correctly you should be doing ob_start() after ob_get_clean()

<?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);
?>

OTHER TIPS

You need to call ob_start() again every time before calling ob_get_clean().

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);

ob_get_clean turns off output buffering. It should really only give you the 1st one. It's showing two because you have a 2nd layer of output buffering active.

Try using:

$text[] = ob_get_contents();
ob_clean();

From php.org:

ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().

ob_get_clean()

When ob_end_clean() is called, it turns off buffering. You need to call ob_get_start() again, to turn buffering back on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top