PHP Output Buffering Explained
What is output buffering?
If you output some html or javascript code, or use echo or print then the output will be sent to browser. But if you use the output buffer then it will store the content in the internal buffer instead of sent to browser. It will store the content on the server untill the script has finished the executing or untill we perform any king of operation on the buffer.
How to Start Output Buffer?
We must have to start output buffer before anything being sent to the browser, so be sure that start it just after the php tag. Check below code for this:
<?php ob_start(); ?>
Make sure that there is nothing before the php tag, even blank space will create a error in this case.
How to send output buffer to browser?
Now if you want to send the output to the browser then you can simply use the ob_flush() function for this. Check below code:
<?php ob_flush(); ?>
However after displaying the content using ob_flush(), it will continue buffering the content which is sent to the browser. But if you want to send the content to the browser and stop the buffering, this can be achieved by the below code:
<?php ob_end_flush(); ?>
How to delete Output Buffer?
At some stage you wish to delete whatever store in the buffer they you should use below function to delete the buffer:
<?php ob_clean(); ?>
just like the ob_flush(), above function will continue to buffer the content after ob_clean() function call.
If you wish to delete the buffer and stop the buffering you should use below code:
<?php ob_end_clean(); ?>
How to get Output Buffer Content?
At some stage if you want to get whatever stored in buffer ( unless you have deleted it or content not sent to browser ), you can use below code to get the buffer content:
<?php $var=ob_get_content(); ?>
Above code means everything echoed after the ob_start() and ob_get_content() will be now in variable $var.
Let us know your suggestion/comments on this.
More From Avinash
- PHP stat() Function Explained
- register_shutdown_function() Explained
- __invoke, __clone and __toString Explained
Avinash Recommends
- PHP Coding Tips (refulzphp)
- Data encryption and hashing in PHP (refulzphp)
