php 将回声捕获到变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/778336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:48:40  来源:igfitidea点击:

capturing echo into a variable

php

提问by OneNerd

I am calling functions using dynamic function names (something like this)

我正在使用动态函数名称调用函数(类似这样)

$unsafeFunctionName = $_POST['function_name'];
$safeFunctionName   = safe($unsafeFunctionName); // custom safe() function

Then I am wanting to wrap some xml around the returned value of the function (something like this):

然后我想在函数的返回值周围包装一些 xml(类似这样):

// xml header etc already created
$result = "<return_value>" . $safeFunctionName() . "</return_value>";

Problem is, sometimes the function returns a value, but sometimes, the function echo's a value. What I want to do is capture that echo into a variable, but, the code I write would need to work either way (meaning, if function returns a value, or echo's a string).

问题是,有时函数返回一个值,但有时,函数 echo 是一个值。我想要做的是将该回声捕获到一个变量中,但是,我编写的代码需要以任何一种方式工作(意思是,如果函数返回一个值,或者回声是一个字符串)。

Not quite sure where to start ~ any ideas?

不太确定从哪里开始〜有什么想法吗?

回答by Paolo Bergantino

Let me preface this by saying:

让我先说:

Be careful with that custom function calling business. I am assuming you know how dangerous this can be which is why you're cleaning it somehow.

小心那个调用业务的自定义函数。我假设您知道这有多危险,这就是您以某种方式清洁它的原因。

Past that, what you want is known as output buffering:

过去,您想要的是输出缓冲

function hello() {
    print "Hello World";
}
ob_start();
hello();
$output = ob_get_clean();
print "--" . $output . "--";

(I added the dashes to show it's not being printed at first)

(我添加了破折号以表明它最初没有被打印)

The above will output --Hello World--

以上将输出 --Hello World--

回答by Tim

PHP: ob_get_contents

PHP:ob_get_contents

ob_start(); //Start output buffer
echo "abc123";
$output = ob_get_contents(); //Grab output
ob_end_clean(); //Discard output buffer

回答by protobuf

In order to use the output value, if present, or the return value if not, you could simply modify your code like this:

为了使用输出值(如果存在)或返回值(如果不存在),您可以简单地修改您的代码,如下所示:

ob_start();
$return_val = $safeFunctionName();
$echo_val = ob_get_clean();
$result = "<return_value>" . (strlen($echo_val) ? $echo_val : $return_val) . "</return_value>";