Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

php - capturing echo into a variable

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 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).

Not quite sure where to start ~ any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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--


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...