Buffering output and storing content in a variable in PHP

I don’t know exactly how output buffering works, but as far as I know, it stores content in some internal variable.

Regarding this, what is the difference from using output buffering and storing content in my local local variable instead of repeating it at the end of the script?

An example with output buffering:

<?php ob_start(); echo "html page goes here"; ob_end_flush(); ?> 

And an example without using output buffering:

 <?php $html = "html page goes here"; echo $html; ?> 

What is the difference?

+4
source share
2 answers

The main differences:

1.) you can use the "normal" output syntax, for example, the echo operator. You do not need to rewrite your problem.

2.) You better control buffering, as buffers can be stacked. You do not need to know about naming conventions, etc., This simplifies the implementation when the record and use sides are implemented separately from each other.

3.) No additional logic requires the output of buffered content, you just flush . It is especially interesting if the output stream is something special. Why burden a control volume with this?

4.) you can use the same output implementation, regardless of whether the output buffer was created. This is a matter of transparency.

5.) you can "catch" accidentally inflated things, such as warnings, etc., and just learn them later.

[...]

+5
source

Output buffering provides greater flexibility in separating output, output, and output problems without requiring any changes to existing code.

You may have existing code that repeats their output rather than returning it; output buffering allows you to run this code without making any changes to it.

Besides the obvious ob_end_flush() you can also use $output = ob_get_contents() and then ob_end_clean() to write the output to the variable again. This allows you to write it to a file rather than displaying it on the screen.

Finally, you can intercept filters in the output buffer system, which allow for instant compression.

See also: ob_gz_handler

+6
source

All Articles