Storing echoed strings in a variable in PHP

2020-02-12 07:32发布

How to grab the string that a function echoes to a variable?

I've go a function similar to this:

    function echoer() {
        echo 'foo';
    }

I cannot change it's source. What I would like to do is to store 'foo' in a variable instead of letting it go to the standard output. How is it done in PHP?

2条回答
叼着烟拽天下
2楼-- · 2020-02-12 07:57
聊天终结者
3楼-- · 2020-02-12 08:00

ob_start() will start an output buffer which will suppress all content. Then, after you have done all the output, call ob_get_contents() and assign it to a variable. Finally call ob_end_clean() to start echoing normally again.

ob_start()

echo "This content won't be echoed immediatley";

$contents = ob_get_contents();

ob_end_clean();

echo $contents;

as Milen mentioned, check out Output Control functions.

This method is very useful, especially for working with Wordpress, which is set to output most things, like comments, and doesn't provide a return function.

查看更多
登录 后发表回答