What is output buffering?

什么是输出缓冲,为什么在PHP中使用它?


Output Buffering for Web Developers, a Beginner's Guide:

Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.

Advantages of output buffering for Web developers

  • Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.
  • All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
  • If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.

  • Output buffering is used by PHP to improve performance and to perform a few tricks.

  • You can have PHP store all output into a buffer and output all of it at once improving network performance.

  • You can access the buffer content without sending it back to browser in certain situations.

  • Consider this example:

    <?php
        ob_start( );
        phpinfo( );
        $output = ob_get_clean( );
    ?>
    

    The above example captures the output into a variable instead of sending it to the browser. output_buffering is turned off by default.

  • You can use output buffering in situations when you want to modify headers after sending content.
  • Consider this example:

    <?php
        ob_start( );
        echo "Hello World";
        if ( $some_error )
        {
            header( "Location: error.php" );
            exit( 0 );
        }
    ?>
    

    The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.

    http://php.net/manual/en/book.outcontrol.php

    More Resources:

    Output Buffering With PHP

    链接地址: http://www.djcxy.com/p/5920.html

    上一篇: 我怎样才能重定向并追加stdout和stderr到Bash文件?

    下一篇: 什么是输出缓冲?