PHP output buffering? What's the best practise?

后端 未结 3 971
北荒
北荒 2021-01-19 18:17

Further to my previous question, what\'s the best approach when I want to buffer PHP output until I have performed all processing? I want to buffer to leave myself the optio

相关标签:
3条回答
  • 2021-01-19 18:40

    Well written code needs no output buffering. By that I mean: first, you do all your processing, without any output. Business logic, validation, database access - this kind of stuff. After this is done, you can close the DB connection, the session, etc. because all you do is create your output based on data collected above.
    This method usually results in far better maintainable code.

    0 讨论(0)
  • 2021-01-19 18:52

    I open a buffer with ob_start(); ( http://php.net/manual/en/function.ob-start.php )

    Then anything that would normally be sent to the browser (except headers) is stored in the buffer until I close it. When I want to output or manipulate the buffer, I access it like this:

    $buffer = ob_get_clean(); ( http://php.net/manual/en/function.ob-get-clean.php )

    There are lots of other buffer options here:

    http://www.php.net/manual/en/ref.outcontrol.php

    This is the best way in my opinion because you don't have to keep adding items to the buffer; PHP is automatically capturing everything as long as the buffer is open.

    0 讨论(0)
  • 2021-01-19 18:53

    For me, I did this:

    <?php
    
    ob_start();
    
    //do your process here
    
    if($error)
    {
      ob_end_clean();
      header('Location: /some/path.php');
      exit;
    }
    ob_end_flush();
    
    ?>
    
    0 讨论(0)
提交回复
热议问题