ob_start - save php output to a string - The PHP output buffering

I want to share this great php utility: the output buffering, it is sometimes very usefull. So what it does ?
The PHP output buffering will save all the server outputs ( html and php prints) to a string variable.

So to start buffering, use ob_start(); this will keep saved any output.
Then you use $variable = ob_get_clean(); to stop buffering, and copy the buffer content to the variable.

Here are few samples of the use of ob_start() and ob_get_clean()


<?php ob_start(); //Turn on output buffering ?>
Hello world, <a href="http://www.blogger.com/myotherpage.php">link</a>
<div class="style">Content</div>
<?php $var = ob_get_clean(); //copy current buffer contents into $message variable and delete current output buffer ?>


Now the content of the variable $var should be:

Hello word, <a href="http://www.blogger.com/myotherpage.php">link</a>
<div class="style">Content</div>


Another example (with php outputs buffered)

<?php ob_start(); ?>
Hello world, <?php echo "My Website"; ?>
Thank you.
<?php $var = ob_get_clean(); ?>


And this will be the content of $var:
Hello world, My Website
Thank you.

That's all !

299 comments:

«Oldest   ‹Older   401 – 299 of 299   Newer›   Newest»
«Oldest ‹Older   401 – 299 of 299   Newer› Newest»