Blogroll

Monday, October 10, 2011

Save buffer output in Php

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();
When you run this code, the output is nothing because
   ob_end_clean();
clean all your output. To display the output to browser. You just need
echo $string
after
 ob_end_clean();
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:
Source:http://php.assistprogramming.com/php-buffer-output-put-contents-in-a-variable.html
Olá! Se você ainda não assinou, assine nosso RSS feed e receba nossas atualizações por email, ou siga nos no Twitter.
Nome: Email:

0 comments:

Post a Comment