Assigning results of the PHP echo statement(s) to a value of a variable
Once in a while you might realize that you wish your code snippet had saved its output into a variable instead of displaying it on screen with echo. If the snippet is long and complicated it can take awhile to rewrite it and fix errors that prone to appear on the way. The quick work-around is to use a few functions that deal with output buffering in a certain way:
// Start output buffering:
ob_start();
// While output buffering is active no output is sent
// from the script (other than headers), instead
// the output is stored in an internal buffer.
/* -- A part of the snippet that normally would display some text -- */
echo '<div>Today is ';
echo date('r');
echo '</div>';
/* ----------------------------------------------------------------- */
// Save the echoed output into the $html variable:
$html = ob_get_contents();
// Clean the output buffer and turn off output buffering in one step:
ob_end_clean(); // Cleaning won't let the echoed output get on the screen.
/* ... Use the $html variable in the rest of your program ... */
This is similar to command substitution used in Bourne-style shells (sh, zsh, bash and others), like so:
somevar=`printf 'Today is '; date`
in PHP, output buffering can be nested as well:
ob_start();
/* ================ */
/* == Outer Part == */
echo '<div>Today is ';
/* ---------------- */
/* -- Inner Part -- */
ob_start();
echo 'Some Text';
$text = ob_get_contents();
ob_clean();
/* -- End of Inner Part -- */
/* ----------------------- */
echo date('r');
echo '</div>';
/* == End of Outer Part == */
/* ======================= */
$html = ob_get_contents();
ob_clean();
Output:
Today is Wed, 10 Feb 2021 08:24:50 +0100
Some Text
This page was last updated on February 25, 2021