Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I capture the result of an echo() into a variable in PHP?

Tags:

php

echo

capture

I'm using a PHP library that echoes a result rather than returns it. Is there an easy way to capture the output from echo/print and store it in a variable? (Other text has already been output, and output buffering is not being used.)

like image 827
Luke Dennis Avatar asked Oct 30 '10 20:10

Luke Dennis


People also ask

Where does PHP echo output go?

Echo simply outputs the strings that it is given, if viewing in the browser it will output the strings to the browser, if it's through command line then it will output the strings to the command line.

Is echo a variable in PHP?

Definition and Usage The echo() function outputs one or more strings. Note: The echo() function is not actually a function, so you are not required to use parentheses with it. However, if you want to pass more than one parameter to echo(), using parentheses will generate a parse error.

What does the echo statement do in PHP?

PHP echo statement can be used to print the string, multi-line strings, escaping characters, variable, array, etc. Some important points that you must know about the echo statement are: echo is a statement, which is used to display the output. echo can be used with or without parentheses: echo(), and echo.

What is echo tag in PHP?

Description ¶ echo(string ...$expressions ): void. Outputs one or more expressions, with no additional newlines or spaces. echo is not a function but a language construct. Its arguments are a list of expressions following the echo keyword, separated by commas, and not delimited by parentheses.


3 Answers

You could use output buffering :

ob_start();

function test ($var) {
    echo $var;
}

test("hello");
$content = ob_get_clean();

var_dump($content); // string(5) "hello"

But it's not a clean and fun syntax to use. It may be a good idea to find a better library...

like image 75
Vincent Savard Avatar answered Sep 21 '22 02:09

Vincent Savard


The only way I know.

ob_start();
echo "Some String";
$var = ob_get_clean();
like image 35
Cesar Avatar answered Sep 22 '22 02:09

Cesar


You should really rewrite the class if you can. I doubt it would be that hard to find the echo/print statements and replace them with $output .=. Using ob_xxx does take resources.

like image 28
Xeoncross Avatar answered Sep 19 '22 02:09

Xeoncross