PHP Tip: Redirecting echo output

I've been designing a new theme for the blog (using WordPress 1.3), and in doing so ran into a problem where some of the WordPress supplied functions printed instead of returning the string I was interested in. One example is the comment_author() function, which prints (using echo) the author of a particular comment. I did a bit of research and eventually found a way to "redirect" the output into a variable, so I could use it in the other code.

Note: I know very little about PHP, so this is probably a very kludgy, very ineffective hack. If anyone can suggest a better solution, I'll listen!

Hopefully someone will find this of use…

Thanks to this article, I found out that you can use output buffering in PHP to "collect" anything printed or echoed and save it for later use.

My aim was to get the output of the comment_author() function, and then use it in an if () statement to check if the author was me.

Here's the code I used, with explanations in the comments:

<?php
/* We want to find out who the author is, but not
echo it. */

// Start output buffering
ob_start();

// Run the function echoing the output
comment_author();

// Assign a variable to the contents of the buffer
$author = ob_get_contents();

// Close the buffer and clean it
ob_end_clean();

// Set the default value
$jeremy = 0;

// Check if the returned author was me
if ($author == 'Jeremy Higgs') {
$jeremy = 1;
}
?>

… and that's that! The output from the comment_author() function is saved to the $author variable, for later use!

10 Responses to “PHP Tip: Redirecting echo output”


Leave a Reply