You can do this by buffering the output :
function include2string($file) { ob_start(); include($file); return ob_get_clean(); }
@DaveRandom indicates (correctly) that the problem with the wrapper in the function is that your script ($ file) will not have access to the variable defined globally. This may not be a problem for many scripts included dynamically, but if this is a problem for you, then this method can be used (as others have shown) outside the shell of functions.
** Import Variables One thing you can do is add the dataset that you would like to present to your script variables. Think about how to pass data to a template.
function include2string($file, array $vars = array()) { extract($vars); ob_start(); include($file); return ob_get_clean(); }
You would call it this way:
include2string('foo.php', array('key' => 'value', 'varibleName' => $variableName));
and now $key and $variableName will be visible inside your foo.php file.
You can also provide a list of global variables for "import" for your script, if that seems more understandable to you.
function include2string($file, array $import = array()) { extract(array_intersect_key($GLOBALS, array_fill_keys($import, 1))); ob_start(); include($file); return ob_get_clean(); }
And you would name it by providing a list of global characters that you would like to open with a script:
$foo='bar'; $boo='far'; include2string('foo.php', array('foo'));
foo.php should be able to see foo , but not boo .
Prestaul
source share