To Turn On Output Buffering:
To add following line of code before you start actually generating the page:
// Start output buffering. All output is stored in output buffer of PHP ob_start();
By default, Output buffering is in OFF mode. and above line of code turns on output buffering.All output is stored in an internal buffer. After than you can add or write the PHP code into a page.
NOTE: Always call ob_start( ) at the top of your page and ob_end_flush( ) at the bottom.
To take content from Output Buffer:
After all the content is generated, you take the content and flush it by adding the following line of code.
// To fetch the output and store it in $output $output = ob_get_contents();
ob_get_contents() function returns the current contents of the output buffer as a string. You can then do whatever you want with it.
To Send Output Buffer to browser
//To clean the output buffer ob_flush();
Here,ob_flush() is used to discard the content of the buffer whereas ob_end_flush() flushes the entire buffer and turn off output buffering.
// stop output buffering and clean the output buffer ob_end_flush();
ob_flush() is used when you want to flush section of the page to the client, whereas ob_end_flush() flushes the entire buffer, then destroys the buffer.
NOTE: The output won’t be sent until ob_flush() or ob_end_flush( ) is called
ob_end_flush() stops buffering and sends the current contents of the buffer to the browser.
To Flush Output Buffer
If you just wanted to take the contents into a string and not want to send those contents into the browser, you could call ob_end_clean() to end output buffering and which destroy the contents of the buffer.
NOTE:It is important to note that both ob_end_flush() and ob_end_clean() destroy the buffer. In order to capture the buffer’s contents for later use, you need to make sure to call ob_get_contents() before you end buffering.
Let’s see example for Output buffering:
echo "Hello CreativeDev"; header("Content-Type: text/plain");
and You get below error:
Cannot add header information – headers already sent
All the headers must be sent at the beginning of the response because by default PHP sends out content as it comes and if you send headers after page text, you will get an error.With output buffering, the transmission of the response awaits a call to flush() and the headers are sent synchronously. so the following works fine:
ob_start(); echo "Hello CreativeDev"; header("Content-Type: text/plain"); ob_end_flush();
Basically, Output buffering can be used to improve network performance and implementing content compression.