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
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.
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...
The only way I know.
ob_start();
echo "Some String";
$var = ob_get_clean();
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();