Output Buffering

  // Start buffering

  // 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

  // Do stuff to $getContent as needed

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



  1. andrew

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


  2. David

    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. marcusklaas

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


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

    instead of

    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. Dennis
    Permalink to comment#

    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
    Permalink to comment#

    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.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.