I'm using a PHP library that echoes a result rather than returns it. Is there an easy way to capture the output from echo/print and store it in a variable? (Other text has already been output, and output buffering is not being used.)
+3
A:
The only way I know.
ob_start();
echo "Some String";
$var = ob_get_clean();
Cesar
2010-10-30 20:33:10
+3
A:
You could use output buffering :
ob_start();
function test ($var) {
echo $var;
}
test("hello");
$content = ob_get_clean();
var_dump($content); // string(5) "hello"
But it's not a clean and fun syntax to use. It may be a good idea to find a better library...
Vincent Savard
2010-10-30 20:35:09
ob_start() function documentation provides some details: http://www.php.net/manual/en/function.ob-start.php
Kel
2010-10-30 20:37:02
`ob_get_contents()` will capture whatever was echoed, but it will not prevent it from being sent to the browser at a later time. The string will be captured _and_ echoed. If you want to capture _instead of_ echoing, you should use `ob_get_clean()`
kijin
2010-10-30 20:39:01
You are entirely right kijin, I edited a bit before your comment.
Vincent Savard
2010-10-30 20:42:19
A:
Its always good practise not to echo data until your application as fully completed, for example
<?php
echo 'Start';
session_start();
?>
now session_start
along with another string of functions would not work as there's already been data outputted as the response, but by doing the following:
<?php
$output = 'Start';
session_start();
echo $output;
?>
This would work and its less error prone, but if its a must that you need to capture output then you would do:
ob_start();
//Whatever you want here
$data = ob_get_contents();
//Then we clean out that buffer with:
ob_end_clean();
RobertPitt
2010-10-30 20:40:02
+1
A:
You should really rewrite the class if you can. I doubt it would be that hard to find the echo/print statements and replace them with $output .=
. Using ob_xxx does take resources.
Xeoncross
2010-10-30 20:48:34