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?
我无法改变它的来源。我想做的是将foo存储在变量中,而不是让它进入标准输出。如何在PHP中实现?
2 个解决方案
#1
17
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()将启动一个输出缓冲区,该缓冲区将抑制所有内容。然后,在完成所有输出之后,调用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;
as Milen mentioned, check out Output Control functions.
正如Milen提到的,请检查输出控制函数。
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.
这个方法非常有用,特别是对于Wordpress, Wordpress被设置为输出大多数东西,比如注释,并且不提供返回函数。
#1
17
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()将启动一个输出缓冲区,该缓冲区将抑制所有内容。然后,在完成所有输出之后,调用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;
as Milen mentioned, check out Output Control functions.
正如Milen提到的,请检查输出控制函数。
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.
这个方法非常有用,特别是对于Wordpress, Wordpress被设置为输出大多数东西,比如注释,并且不提供返回函数。