How to execute and get content of a .php file in a variable?

You have to differentiate two things:

  • Do you want to capture the output (echo, print,…) of the included file and use the output in a variable (string)?
  • Do you want to return certain values from the included files and use them as a variable in your host script?

Local variables in your included files will always be moved to the current scope of your host script – this should be noted. You can combine all of these features into one:

include.php

$hello = "Hello";
echo "Hello World";
return "World";

host.php

ob_start();
$return = include 'include.php'; // (string)"World"
$output = ob_get_clean(); // (string)"Hello World"
// $hello has been moved to the current scope
echo $hello . ' ' . $return; // echos "Hello World"

The return-feature comes in handy especially when using configuration files.

config.php

return array(
    'host' => 'localhost',
     ....
);

app.php

$config = include 'config.php'; // $config is an array

EDIT

To answer your question about the performance penalty when using the output buffers, I just did some quick testing. 1,000,000 iterations of ob_start() and the corresponding $o = ob_get_clean() take about 7.5 seconds on my Windows machine (arguably not the best environment for PHP). I’d say that the performance impact should be considered quite small…

Leave a Comment