How to get echo () result in a variable in PHP?

I am using a PHP library that repeats the result, but does not return it. Is there an easy way to capture the output from echo / print and save it in a variable? (Other text has already been output, but output buffering is not used.)

+4
source share
4 answers

You can use output buffering:

ob_start(); function test ($var) { echo $var; } test("hello"); $content = ob_get_clean(); var_dump($content); // string(5) "hello" 

But this is not a clean and fun syntax to use. It might be a good idea to find the best library ...

+11
source

The only way I know.

 ob_start(); echo "Some String"; $var = ob_get_clean(); 
+4
source

You really have to rewrite the class if you can. I doubt it would be difficult to find the echo / print instructions and replace them with $output .= . Using ob_xxx requires resources.

+1
source

Its always good practice - not echo data until your application is completely complete, for example

 <?php echo 'Start'; session_start(); ?> 

now session_start along with another line of functions will not work, since there was already data output as an answer, but by doing the following:

 <?php $output = 'Start'; session_start(); echo $output; ?> 

This will work and be less error prone, but if necessary to capture the output, you should:

 ob_start(); //Whatever you want here $data = ob_get_contents(); //Then we clean out that buffer with: ob_end_clean(); 
0
source

All Articles