Reputation: 35235
You know how print_r
accepts an optional 2nd parameter that if set to true
will return the result instead of printing it?
I wish include
accepted a 2nd parameter that would work the same way.
It doesn't so what are the available alternatives? How can I include a file into a variable?
Upvotes: 1
Views: 100
Reputation: 14705
I think you are looking for #5 at http://www.php.net/manual/en/function.include.php
return stuff from a script.
include handles a return value from the script.
Upvotes: 0
Reputation: 99879
ob_start()
and ob_get_clean()
will do that for you:
ob_start();
include "file.php";
$result = ob_get_clean();
After ob_start() everything echoed is captured, and ob_get_clean() is used to retrieve the captured data.
You can even do an include2
function like this:
function include2($file) {
ob_start();
include $file;
return ob_get_clean();
}
And use it like this:
include2("file.php"); // return all printed values instead of really printing them
As noted by @ircmaxell, this include2
function does not behave exactly the same as include
since the scope of the include changes (from global to the function's scope). So this could potentially break things if you rely on the global scope.
Upvotes: 7