HomeDefault

Importance and Benefits of PHP Output Buffering & how can I set it?

Like Tweet Pin it Share Share Email

PHP sends data from server to client/browser as soon as it is ready – this response might be line by line or by code blocks.Output buffering enables you to store up your output and send it when you are ready to go or to not send it at all, if you decide.

 

or simple

 

Output buffering puts your PHP script’s output/response in a buffer instead of sending it directly to the browser in pieces, allowing you to update your webpage as a whole before the user see.

 

1.Start Output Buffer

You have to start the output buffer before anything is sent to the browser.So one of the ways to ensure that is starting it right after you opened the php tag.

 

2.Send Output Buffer to Browser

If at any time you wish to send the content of the buffer to the browser you can do simply by the following line.
ob_flush();

After this point however the output buffer will continue to buffer the content which is send to the browser.
If you which to simply send the content of the buffer and stop using it you can do this with the following code.

ob_end_flush();

 

3.Delete Output Buffer

In some circumtances you might wish to delete whatever is stored in the output buffer.You can do this by using the following command.
ob_clean();

 

4.Get Output Buffer Content

If you started the output buffer you can get the content of it at any time (unless you have deleted it or sent it to the browser.This is done by the following line

<?php $myvar = ob_get_contents();?>

This means that everything you echo or would be sent otherwise to the browser between this line and the ob_start(); will now be in $myvar.

Here is small example of output buffering

<?php
ob_start();
include('tpl_scriptarticle.php');
$title = 'Hello All';
$myvar = ob_get_contents();
ob_clean();
echo $myvar;
?>

There are some more function , you can get more by this link click here