Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capturing echo into a variable

Tags:

php

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?

like image 746
OneNerd Avatar asked Apr 22 '09 17:04

OneNerd


People also ask

Can we store echo in variable PHP?

echo is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function.

How do you echo an HTML variable?

'</span>'; Additionally, you can do it inline by escaping the double quotes: echo "<span class=\"label-$variable\">$variable</span>"; Using double quotes also allows for special characters such as \n and \t .

What is the use of echo function?

In computing, echo is a command that outputs the strings that are passed to it as arguments. It is a command available in various operating system shells and typically used in shell scripts and batch files to output status text to the screen or a computer file, or as a source part of a pipeline.


2 Answers

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

like image 149
Paolo Bergantino Avatar answered Sep 19 '22 07:09

Paolo Bergantino


PHP: ob_get_contents

ob_start(); //Start output buffer echo "abc123"; $output = ob_get_contents(); //Grab output ob_end_clean(); //Discard output buffer 
like image 34
Tim Avatar answered Sep 21 '22 07:09

Tim