How to prevent echo in PHP and catch what it is inside?

ilhan picture ilhan · Aug 17, 2011 · Viewed 20.7k times · Source

I have a function ( DoDb::printJsonDG($sql, $db, 1000, 2) ) which echos json. I have to catch it and then use str_replace() before it is send to the user. However I cannot stop it from doing echo. I don't want to change printJsonDG because it is being used in several other locations.

Answer

olivier picture olivier · Aug 17, 2011

You can use the ob_start() and ob_get_contents() functions in PHP.

<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>

Will output :

string(6) "Hello "
string(11) "Hello World"