Why use output buffering in PHP?

前端 未结 11 1012
礼貌的吻别
礼貌的吻别 2020-12-09 02:43

I have read quite a bit of material on Internet where different authors suggest using output buffering. The funny thing is that most authors argument for its use only becaus

相关标签:
11条回答
  • 2020-12-09 03:08

    Output buffering is critical on IIS, which does no internal buffering of its own. With output buffering turned off, PHP scripts appear to run a lot slower than they do on Apache. Turn it on and they run many times faster.

    0 讨论(0)
  • 2020-12-09 03:13

    The most obvious use cases are:

    1. An output filter (eg ob_gzhandler or any number of filters you could devise on your own); I have done this with APIs that only support output (rather than return values) where I wanted to do subsequent parsing with a library like phpQuery.
    2. Maintenance (rather than rewriting) of code written with all the problems you discuss; this includes things like sending headers after output began (credit Don Dickinson) or suppression of certain output that has already been generated.
    3. Staggered output (credit here to Tom and Langdon); note that your tests may have failed because it conflicts with PHP/Apache's default internal buffer, but it is possible to do, it simply requires a certain amount to be flushed before PHP will send anything—PHP will still keep the connection open though.
    0 讨论(0)
  • 2020-12-09 03:17

    I use output buffering in order to avoid generating HTML by string concatenation, when I need to know the result of a render operation to create some output before I use the rendering.

    0 讨论(0)
  • 2020-12-09 03:17

    Use output buffering to cache the data in a file, for other similar requests if you are doing a lot of database transactions and processing.

    0 讨论(0)
  • 2020-12-09 03:18

    It's an old question but nobody said that an important feature of outbut buffering is filtering. It is possible to preprocess the buffer before sending it to the client.

    This is a very powerful concept and opens many intriguing possibilities. In a project I used two filters simultaneously:

    1. ad-hoc translation of terms (replacement of short texts)
    2. obfuscation of HTML, CSS and Javascript (don't ask me why)

    To enable output filtering call ob_start("callback") where callback is the name of the filtering function. For more details see PHP's manual for ob_start: http://php.net/manual/en/function.ob-start.php

    0 讨论(0)
提交回复
热议问题