What is an "output_buffer"?

4

Reading is answer , this question came to me.

What is a output_buffer ?

    
asked by anonymous 17.02.2017 / 19:47

1 answer

5

Buffer

When we talk about buffer we are talking about buffer data, not to confuse with the term used in other contexts even in computing.

It is a memory area reserved for temporary storage of data, usually when you are going to carry it from one place to another.

The buffer can be a simple variable with a reserved amount of bytes or some more complex structure.

Buffer is an abstract concept, it always materializes through another mechanism, usually a variable.

Template

PHP works with a page template system. So everything that is not PHP code is text that will be sent to the HTTP server.

PHP codes can generate new text dynamically inserted in the page, usually as echo or print .

PHP is actually a language that always generates text as output. And all the code does is determine what code that is.

In most languages a command print or echo would print the text on the screen. PHP can work that way too. But the most common is it provide pages and other web elements to the HTTP server. It would not make sense to write on the screen.

Everything that the code orders to print, including the parts outside the tags <?php ... ?> is sent to the server.

Output

To avoid this jagged thing and give more flexibility we can use a buffer to store everything that would be sent to the server and we can control when to send to the server if we want it. p>

In the PHP library you have the option to bind and manipulate the contents of this buffer . This is what was done in that answer.

There is not much secret, in the family of functions started by ob_ we have to start the buffer , get the data and terminate cleaning or releasing the data to the server.

If you plan well, you can do the same manually without these functions. Instead of just printing you are already manipulating a variable specifically created to be buffer .

Documentation .

Header

In direct shipment to the server you have to think about the order to do things. You can not send something that needs to come before it has been sent. For example, you can not send an HTTP header after you started sending the page itself.

With buffer you can. So how do I use a variable to concatenate the entire script result.

Example:

<?php
    ob_start();
    echo "1 : Hello\n";
    ob_start();
    echo "2 : Hello";
    var_dump(ob_get_clean());
    echo "3 : Hello";
    //http://pt.stackoverflow.com/q/184952/101
?>

See running on ideone . And in PHP Sandbox . Also put it on GitHub for future reference .

    
18.02.2017 / 13:50