Reputation: 7693
Imagine the following:
<?php
echo 'foo';
echo 'bar';
?>
Simple, right? Now, what if at the end of this simple script I need to have everything I've echoed in that script in a variable, like:
<?php
echo 'foo';
echo 'bar';
// $end // which contains 'foobar';
?>
I tried this:
<?php
$end = NULL;
echo $end .= 'foo'; // this echoes foo
echo $end .= 'bar'; // this echoes foobar (this is bad)
// $end // which contains 'foobar' (this is ok);
?>
But it doesn't work, as it appends the data, therefore echoes the appended data (duplicated). Any way to do this?
EDIT: I cannot use OB, as I'm already using it in the script in a different way (I'm simulating a CLI-output in a browser).
Upvotes: 0
Views: 2217
Reputation: 1015
Apparently I was misunderstanding: so then I'd suggest this:
<?php
$somevar = '';
function record_and_echo($msg,$record_var) {
echo($msg);
return ($msg);
}
$somevar .= record_and_echo('foo');
//...whatever else//
$somevar .= record_and_echo('bar');
?>
old: Unless I'm misunderstanding this'll do that fine:
<?php
$output = ''
$output .= 'foo';
$output .= 'bar';
echo $output;
?>
Upvotes: 1
Reputation: 1265
OB can be nested:
<?php
ob_start();
echo 'some output';
ob_start();
echo 'foo';
echo 'bar';
$nestedOb = ob_get_contents();
ob_end_clean();
echo 'other output';
$outerOb = ob_get_contents();
ob_end_clean();
echo 'Outer output: ' . $outerOb . '' . "\n" . 'Nested output: ' . $nestedOb;
The result:
Outer output: some outputother output;
Nested output: foobar
Upvotes: 0
Reputation: 4835
I'm not really sure what you are trying to accomplish, but consider output buffering:
<?php
ob_start();
echo "foo";
echo "bar";
$end = ob_get_clean();
echo $end;
Upvotes: 0