Output Control

PHP offers a great deal of flexibility as to how you want to output your content. In general use, PHP is embedded inside HTML in code islands started with <?php and ended with ?>.

You can reverse this by writing your whole script as one big PHP code island and printing HTML as necessary. Going back to the example shown previously, we can make our PHP code look almost identical to the Perl code by printing the HTML from inside our PHP code:

    print "<html>\n";
    print "<body>\n";
    print "<p>Welcome, $Name</P>\n";
    print "</body>\n";
    print "</html>\n";

"Print" is a simple function that outputs a chunk of text, enclosed in quotation marks, to the client. "\n" means "start new line in the source code", and it serves to lay the source code out nicely. For the longest time, a debate raged on messageboards and mailing lists as to whether it was faster to drop out of "PHP mode" to output large amounts of HTML, or whether it was just as fast to stay in PHP mode. The truth is that it is horses for courses - you will find little or no speed difference either way.

PHP purists like to point out that print is technically not a function, and, technically, they are correct. This is why print doesn't require brackets around the data you pass to it. Other language constructs that masquerade as functions (and are referred to as functions herein for the sake of sanity) include echo, include, require, and exit.

PHP also has great output buffering features that further increase your control over the flow of output. An output buffer can be thought of as a storage hole where you can queue up content for outputting. Once you start a buffer, any output you create is automatically put into that buffer, and is not seen unless the buffer is closed and flushed - that is, sent to your visitor.

The advantage to this output queuing is two-fold. First, it allows you to clean the buffer if you decide not to output the current output queue in the buffer. When a buffer is cleaned, all the output stored in there is deleted as if it were never there, and output for that buffer is started from scratch.

Secondly, output buffering allows you to break the traditional ordering of web pages - that of headers first and content later. Owing to the fact that you queue up all your output, you can send content first, then headers, then more content, then finally flush the buffer. PHP internally rearranges the buffer so that headers come before content.

Output buffering is covered in much more depth later.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Performance >>

Previous chapter: Interpreting vs. Compiling

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.