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:

10 responses to “PHP: How to capture output of echo into a local variable.”

  1. Andrew says:

    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. wp_user says:

    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. Jim says:

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

  5. dVyper says:

    This has helped me. Thanks 🙂

  6. Bill says:

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

  7. Craig says:

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

  8. Jeff says:

    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. Bradford says:

    Thanks! This helped alot when modifying a MediaWiki theme.

  10. ninj says:

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