将回显的字符串存储在PHP中的变量中 [英] Storing echoed strings in a variable in PHP

查看:87
本文介绍了将回显的字符串存储在PHP中的变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取函数回显到变量的字符串?

我已经执行了类似的功能:

    function echoer() {
        echo 'foo';
    }

我无法更改其来源.我想做的是将'foo'存储在变量中,而不是让它进入标准输出.如何在PHP中完成?

解决方案

ob_start()将启动一个输出缓冲区,该缓冲区将禁止所有内容.然后,在完成所有输出之后,调用ob_get_contents()并将其分配给变量.最后,调用ob_end_clean()重新开始正常回声.

ob_start()

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

$contents = ob_get_contents();

ob_end_clean();

echo $contents;

正如Milen所提到的,请查看输出控制功能.

此方法非常有用,特别是对于使用Wordpress而言,该方法设置为输出大多数内容,例如注释,并且不提供返回功能.

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?

解决方案

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.

这篇关于将回显的字符串存储在PHP中的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆