Are you familiar with PHP’s output buffering? You should be. If you already are, you can disregard this post.
When we print, echo, provide inline HTML, etc., PHP’s default default behavior is to write to the standard output. Typically that means the web browser or terminal you’re using to execute the script. But this isn’t always ideal. Sometimes we need to capture the output of one script for use in another script. We want to include it, but instead of printing the results to a user, we would like to store them in a variable. PHP’s output buffering allows us to do just that, using simple output control functions like ob_start(), ob_get_contents(), and ob_end_clean().
-
// Turn on output buffering.
-
ob_start();
-
-
// Execute a script.
-
// Results go into the output buffer instead of the standard output.
-
include(‘template.php’);
-
-
// Return the contents of the output buffer.
-
$html = ob_get_contents();
-
-
// Clean the output buffer and turn off output buffering.
-
ob_end_clean();
Using these functions to capture the output of a presentational template is just one real-world example. Understanding it is one step toward adding a familiarity with output buffering and other output control functions to your personal PHP toolbox.
Leave a Reply
You must be logged in to post a comment.