Code Snippet

Home » Code Snippets » PHP » Output Buffering

Output Buffering

<?php

  // Start buffering
  ob_start();

  // Output stuff (probably not this simple, might be custom CMS functions...
  echo 'Print to the screen!!!';

  // Get value of buffering so far
  $getContent = ob_get_contents();

  // Stop buffering
  ob_end_clean();

  // Do stuff to $getContent as needed

  // Use it
  echo 'Now: ' . $getContent;

?>

Subscribe to The Thread

  1. andrew

    Thanks for all you help. You really helped me understand web programming and css magic :)

    -andrew

  2. We use this all the time for processing forms. The output buffer acts as a space for us to compose HTML email receipts for filling out a form, then we just throw that into a variable and send it out. It’s the cleanest way!!

  3. Instead of buffering, it is probably easier to just save output to a string and keep appending that.

    So

    $output = 'yoyo, waddup holmes';
    $output .= 'hai';
    echo $output;

    instead of

    b_start();
    echo 'yoyo, waddup holmes';
    echo 'hai;
    $output = ob_get_contents();
    echo $output;

    • Michael Laddie

      I think you may be missing the point a little.
      The string has probably been used for quickness within the example.

      You can implement caching by using output buffering. Place the buffer start before your output begins and the buffer content capture and clean after the output is complete and then save the content to a cache file…

      Buffering also allows headers() to be implemented after output has began.

  4. Could this be used in a cache system ? For example when rebuilding a cache to take the output and write it to a cache file and use it ? Is it practical to do so ?

  5. GregoryD

    There are more practical caching suites like memcached and varnish that are better suiting to caching output. You will see buffering used a lot of times in frameworks where dynamic content is buffered and then fed into a static template. This allows you to separate your code from your design. Nobody likes to work with giant messy Dreamweaveresque pages.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~