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:
Thanks, just saved me a lot of time and effort figuring this out for myself. I didn’t know where to look in the php documentation for such functions!
Andrew
Simply use get_bloginfo() instead.
@wp_user, thanks for that tip. The specific WordPress example I used was to illustrate how to do the general task of capturing the output of echo() into a local variable.
Thanks, I needed to capture the output of a plugin to replace some text before it was displayed, and your code works great 🙂
This has helped me. Thanks 🙂
Bravo! This is exactly what I was looking for. Thanks for sharing and saving me some precious time!
Great help, this is exactly what I needed working on a shopping cart that was grabbing info from 3 databases, thank you.
Excellent demonstration. I needed to capture the echo outputs from within a bunch of includes, this is precisely what I was looking for. Thanks for posting(and posting reference links – very helpful).
Thanks! This helped alot when modifying a MediaWiki theme.
Dude! thanks a lot! you just saved me hours of banging my head against the wall!!!