PHP buffer output. Put contents in a variable

September 19, 2007

We all know that PHP is default sending all output to the standard output buffer( the browser in many cases if I can say like that.) That depends off course about your server configurations but that’s how it gets setup into the standard. There is a buffer size set in php.ini; when the output buffer is full, it is automatically flushed and sent to the browser.

Many times in our programming life :) we wanted to change this standard way and send the contents to a variable instead of printing to the browser .That is very useful if you want to write in a file as a log or if you just need it in a var for future processing or…whatever.

There is a nice workaround here. The solution comes from using the PHP buffering functions.

Let’s have this example:

<?

echo "here is a string";
?>

This would normally print the string under echo. If we want that value stored in a variable we do something like this:

<?
   ob_start();
  echo "here is a string";
  $string=ob_get_contents();
  ob_end_clean();

?>

Now, into the $string variable we would have what the previous echo example displayed.

The idea is simple: The ob_Start() function redirects the output to a buffer. After that all the print, echo are sent to that buffer.

ob_get_contents() returns the content of the buffer and ob_end_clean() kill the buffer, redirecting the output to where it previously was: the standard output.

One useful example of those functions is for example the Wordpress , looked as a CMS. If you ever worked with it, you know about the template function the_content(); That is just echo-ing the content of an article. If you want that in a variable is just simple to use the output buffering functions:

<?
ob_start();
the_content();
$content=ob_get_contents();
ob_end_clean();
?>

Also , it’s very useful to use this functions when you work with template engines such as Smarty or TemplateIT. A tutorial for that will soon come ! Stay posted ;)

Enjoy

 

One Comment for “PHP buffer output. Put contents in a variable”

  1. Joe Says:

    Thankyou very much for this article! I was racking my brains trying to figure out how to do this… Now I can get the output from my CMS system and do what I want with it!

Post a comment

Name (required)

Mail (will not be published) (required)

Website

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word