tags:

views:

60

answers:

4

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
+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
ob_start() function documentation provides some details: http://www.php.net/manual/en/function.ob-start.php
Kel
`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
You are entirely right kijin, I edited a bit before your comment.
Vincent Savard
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
+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