Drahcir
Drahcir

Reputation: 11972

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

Upvotes: 2

Views: 2811

Answers (4)

Naftali
Naftali

Reputation: 146310

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

Upvotes: 7

mvanlamz
mvanlamz

Reputation: 91

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.

Upvotes: 4

gen_Eric
gen_Eric

Reputation: 227240

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

Upvotes: 5

Ennui
Ennui

Reputation: 10190

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

Upvotes: 5

Related Questions