Tutorial by Examples

Output buffering allows you to store any textual content (Text, HTML) in a variable and send to the browser as one piece at the end of your script. By default, php sends your content as it interprets it. <?php // Turn on output buffering ob_start(); // Print some output to the buffer (via...
You can nest output buffers and fetch the level for them to provide different content using the ob_get_level() function. <?php $i = 1; $output = null; while( $i <= 5 ) { // Each loop, creates a new output buffering `level` ob_start(); print "Current nest level: &quo...
In this example, we have an array containing some data. We capture the output buffer in $items_li_html and use it twice in the page. <?php // Start capturing the output ob_start(); $items = ['Home', 'Blog', 'FAQ', 'Contact']; foreach($items as $item): // Note we're about to step &q...
ob_start(); $user_count = 0; foreach( $users as $user ) { if( $user['access'] != 7 ) { continue; } ?> <li class="users user-<?php echo $user['id']; ?>"> <a href="<?php echo $user['link']; ?>"> <?php echo $user...
<?php ob_start(); ?> <html> <head> <title>Example invoice</title> </head> <body> <h1>Invoice #0000</h1> <h2>Cost: £15,000</h2> ... </body> </html> <?php...
You can apply any kind of additional processing to the output by passing a callable to ob_start(). <?php function clearAllWhiteSpace($buffer) { return str_replace(array("\n", "\t", ' '), '', $buffer); } ob_start('clearAllWhiteSpace'); ?> <h1>Lorem Ipsum&l...
/** * Enables output buffer streaming. Calling this function * immediately flushes the buffer to the client, and any * subsequent output will be sent directly to the client. */ function _stream() { ob_implicit_flush(true); ob_end_flush(); }
ob_start is especially handy when you have redirections on your page. For example, the following code won't work: Hello! <?php header("Location: somepage.php"); ?> The error that will be given is something like: headers already sent by <xxx> on line <xxx>. In or...

Page 1 of 1