PHP: How to capture output of echo into a local variable.

I’ve been customizing a WordPress install and have been needing to capture the output of the bloginfo() function, which simply echo’s a string. I wanted to capture the echo into a variable without actually echo’ing the string. You can do so by leveraging PHP’s output buffering functions. Here’s how you do it:

ob_start();
echo 'Hello World';
$myStr = ob_get_contents();
ob_end_clean();

$myStr will now contain ‘Hello World‘ without actually outputting it to the screen.

Reference: