开发者

Including into a variable

You know how print_r accepts an optional 2nd parameter that if set to true will return the result instead of p开发者_JAVA百科rinting 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜