2

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

Drahcir
  • 11,772
  • 24
  • 86
  • 128
  • When I try it I only get first text in the array. Seems like ob_get_clean has very inconsistent results – StephenTG Jul 23 '13 at 15:02
  • @StephenTG I see what you mean. PHPFiddle works twice: http://phpfiddle.org/lite/code/u4z-us5 but http://phpcodepad.com/ only works once – Drahcir Jul 23 '13 at 15:03

4 Answers4

8

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);
?>
Naftali
  • 144,921
  • 39
  • 244
  • 303
5

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);
Ennui
  • 10,102
  • 3
  • 35
  • 42
4

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();
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
4

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.

mvanlamz
  • 91
  • 1
  • 3