48

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?

3 Answers 3

96

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

Sign up to request clarification or add additional context in comments.

1 Comment

Just a minor point, do you know about the ob_get_clean method?
17

PHP: ob_get_contents

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.