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.)
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.
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.
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.
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.
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...
The only way I know.
ob_start();
echo "Some String";
$var = ob_get_clean();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With