Output Buffering¶
Output buffering, also abbreviated ob, is a mechanism that captures output generated by the application, instead of sending it directly to the browser. The output is held in an internal buffer, and it may be manipulated before it’s actually sent to the client.
The output may be of any format: HTML, text, etc. Output may include HTTP headers, although they are usually managed with dedicated functions.
Output buffering relies on the following functions:
ob_start(): starts buffering; nothing is sent to the browser after this pointob_get_contents(): retrieves the current buffer contents as a stringob_end_flush(): sends the buffer to the browser and turns buffering offob_end_clean(): discards the buffer and turns buffering off (nothing is sent)ob_flush(): sends the buffer but keeps buffering onob_get_clean(): shorthand for get + clean in one step
Output buffers can be nested: it is possible to capture content within another capture.
From the last point, it is recommended to always pair ob_start() with an end function, such as ob_end_flush(). This prevents memory leaks, and extra warnings.
It doesn’t affect CLI scripts, as they have no browser to buffer for.
<?php
$s = 'x';
ob_start();
var_dump($s);
$content = ob_get_clean(); // gets the content, and clean it
// The 3 previous lines could also be achieved with $content = var_dump($s, true);
// process it
$content = str_replace('x', 'X', $content);
// display it again
echo $content; //
?>
See also PHP - simple way to send HTTP headers before a script ends and What is output buffering.
Related : Headers