By default, echo or other output commands will directly send the content to the client (browser). However, after turning on the output buffering, the output will not be sent immediately, but will be saved in the buffer first and will not be output until the buffer is cleared or the script is finished. In this way, we can capture, modify and even redirect the output content during the script running.
ob_get_contents() is used to obtain the content in the current output buffer and return the string. If the output buffering is not enabled, calling the function will return false .
<?php
// Turn on output buffering
ob_start();
// Analog output content
echo "This is what's in the buffer。";
// Get the buffer content
$content = ob_get_contents();
// Process the content,For example, replace string
$processedContent = str_replace("Buffer", "Cache area", $content);
// 清空并关闭Buffer(Optional,Can also be used ob_end_flush() Direct output)
ob_end_clean();
// Manually output the processed content
echo $processedContent;
?>
In the example above:
Use ob_start() to enable output buffering.
The contents output using echo are stored in the buffer.
Read the buffer content to the variable $content via ob_get_contents() .
Replace the content with a string to get $processedContent .
Use ob_end_clean() to clear and close the buffer to prevent repeated output of content.
Finally, manually output the processed content.
If you use simple PHP template rendering, and want to capture the template output and then cache or modify it, output buffering is very useful.
<?php
ob_start();
include 'template.php'; // Template file output HTML
$html = ob_get_contents();
ob_end_clean();
// right $html Cache、Compression or other processing
file_put_contents('cache/page.html', $html);
// Finally output the processed page
echo $html;
?>
Some third-party libraries will output content directly, but you want to intercept these outputs, uniform format or packaging processing.
<?php
ob_start();
third_party_function(); // Direct output内容的函数
$output = ob_get_contents();
ob_end_clean();
// For example, the packaging is JSON Format return
echo json_encode(['data' => $output]);
?>
Before using ob_get_contents() , you must make sure that the buffer is turned on ( ob_start() is called), otherwise false will be returned.
Calling ob_end_clean() can close and clear the buffer without outputting content. Calling ob_end_flush() will close the buffer and output the content.
The output buffer can be nested, and ob_get_contents() only gets the contents of the currently active buffer.
ob_get_contents() is a powerful tool to control the PHP output process. In combination with the output buffering mechanism, it can realize various advanced functions such as template capture, output cache, and dynamic content replacement. Mastering the principles and usage methods of output buffering will greatly enhance your control over PHP output.