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. User Avatar

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


  2. User Avatar

    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. User Avatar

    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;

    • User Avatar
      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. User Avatar
    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. User Avatar
    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!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.