What is an output buffer?

Reading is Answer , I came up with this doubt.

What is a output_buffer ?

Author: Comunidade, 2017-02-17

1 answers

Buffer

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

Is a memory area reserved for temporary storage of data, usually when it will transport 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 a abstract concept, it is always realized through another mechanism, in general a variable.

template

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

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

PHP is actually a language that always generates text as output. And all the code does is determine what code this 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 wouldn't make sense to write on the screen.

Everything that the code sends to print, including parts outside the tags <?php ... ?> it's sent to the server.

Output

To avoid this pecking 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 this.

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

Does not have much secret, in the family of functions started by ob_ we have how to start the buffer, take the data and close by cleaning or dropping the data to the server.

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

Documentation .

Header

In sending direct to the server you have to think about the order of doing things. You can't send something that needs to come in sooner than it's already been sent. For example you cannot send an HTTP header after you have started sending the page properly Dita.

With the buffer can. Just like using a variable to concatenate the entire result of the script .

Example:

<?php
    ob_start();
    echo "1 : Hello\n";
    ob_start();
    echo "2 : Hello";
    var_dump(ob_get_clean());
    echo "3 : Hello";
?>

See working on ideone. E no repl.it. also I put on GitHub for future reference .

 5
Author: Maniero, 2020-11-25 15:59:04