<?php
// Start buffering
ob_start();
// Output stuff (probably not this simple, might be custom CMS functions...
echo 'Print to the screen!!!';
// Get value of buffering so far
$getContent = ob_get_contents();
// Stop buffering
ob_end_clean();
// Do stuff to $getContent as needed
// Use it
echo 'Now: ' . $getContent;
?>
Output Buffering
Chris Coyier
on
Thanks for all you help. You really helped me understand web programming and css magic :)
-andrew
We use this all the time for processing forms. The output buffer acts as a space for us to compose HTML email receipts for filling out a form, then we just throw that into a variable and send it out. It’s the cleanest way!!
Instead of buffering, it is probably easier to just save output to a string and keep appending that.
So
$output = 'yoyo, waddup holmes';
$output .= 'hai';
echo $output;
instead of
b_start();
echo 'yoyo, waddup holmes';
echo 'hai;
$output = ob_get_contents();
echo $output;
I think you may be missing the point a little.
The string has probably been used for quickness within the example.
You can implement caching by using output buffering. Place the buffer start before your output begins and the buffer content capture and clean after the output is complete and then save the content to a cache file…
Buffering also allows headers() to be implemented after output has began.
Just a minor detail. You can save a line by doing
instead of
Could this be used in a cache system ? For example when rebuilding a cache to take the output and write it to a cache file and use it ? Is it practical to do so ?
There are more practical caching suites like memcached and varnish that are better suiting to caching output. You will see buffering used a lot of times in frameworks where dynamic content is buffered and then fed into a static template. This allows you to separate your code from your design. Nobody likes to work with giant messy Dreamweaveresque pages.