Tequila Fish Ran-dumb ramblings of me…

10Feb/09Off

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:

Tagged as: , , , Comments Off
Comments (10) Trackbacks (0)
  1. 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

  2. Simply use get_bloginfo() instead.

  3. @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.

  4. Thanks, I needed to capture the output of a plugin to replace some text before it was displayed, and your code works great :)

  5. This has helped me. Thanks :)

  6. Bravo! This is exactly what I was looking for. Thanks for sharing and saving me some precious time!

  7. Great help, this is exactly what I needed working on a shopping cart that was grabbing info from 3 databases, thank you.

  8. 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).

  9. Thanks! This helped alot when modifying a MediaWiki theme.

  10. Dude! thanks a lot! you just saved me hours of banging my head against the wall!!!


Leave a comment


Trackbacks are disabled.