How do I capture the result of an echo() into a variable in PHP?

Luke Dennis picture Luke Dennis · Oct 30, 2010 · Viewed 11.7k times · Source

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

Answer

Vincent Savard picture Vincent Savard · Oct 30, 2010

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...