Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is PHP Output Buffering?
Output Buffering is a method to tell the PHP engine to hold the output data before sending it to the browser. As we know PHP sends the output data to the browser in pieces, but if we utilize the output buffering mechanism, the output data is stored in a variable and sent to the browser as one piece at the end of the script.
Basic Example
Let's demonstrate with a simple example ?
<?php
ob_start();
echo "Hello";
$ob1 = ob_get_contents();
echo "Tutorials Point";
$ob2 = ob_get_contents();
ob_end_clean();
var_dump($ob1, $ob2);
?>
string(5) "Hello" string(20) "HelloTutorials Point"
How It Works
In the above example, ob_get_contents() grabs all of the data gathered since we called ob_start(), i.e. everything in the buffer. The ob_end_clean() function discards the buffer contents without sending it to the browser.
Common Output Buffering Functions
- ob_start() − Starts output buffering
- ob_get_contents() − Returns the current buffer contents
- ob_end_flush() − Sends buffer contents and stops buffering
- ob_end_clean() − Discards buffer contents and stops buffering
- ob_clean() − Clears the buffer without stopping buffering
Practical Example
Here's an example showing how to capture and manipulate output ?
<?php
ob_start();
echo "Original content";
$content = ob_get_contents();
ob_clean();
// Modify the content
$modified_content = strtoupper($content);
echo $modified_content . " - Modified!";
$final_output = ob_get_contents();
ob_end_clean();
echo $final_output;
?>
ORIGINAL CONTENT - Modified!
Advantages of Output Buffering
- Performance − Turning on output buffering alone decreases the amount of time it takes to download and render HTML in the browser, reducing PHP script execution time
- Header Management − Solves "Warning: Cannot modify header information - headers already sent" errors when setting cookies or redirects
- Content Manipulation − Allows you to modify output before sending it to the browser
- Clean Output − Prevents unwanted whitespace or errors from being sent prematurely
Conclusion
Output buffering is essential for managing PHP output flow, preventing header errors, and improving performance. Use ob_start() to begin buffering and appropriate end functions based on whether you want to send or discard the buffered content.
