Any of the examples in the previous section is an excellent first step toward introducing
PHP into a Web site. Their impact in terms of server load is relatively low. I like to think
of sites using similar approaches as being PHP-enabled, as if they had a small injection of
PHP that makes them extraordinary. The step beyond this is what I think of as PHP-
powered: a site made completely of PHP. In this approach every byte of output comes
from PHP. The print (or echo or printf) function is used to send HTML tags.
Every page is a script inside a single pair of PHP tags.
You might have noticed that most of the examples in the book take this approach. I have
found that while this requires extra time up front, the code is much more maintainable.
Once information is put in the context of a PHP variable, it's easy to add something
dynamic to it later. It also has the advantage of ultimately being more readable as the
page becomes more complex. As a simple example, compare Listing 20.5 to Listing
20.6. The idea is to change the background color of the page depending on the time of
day.
My experience has been that having all the HTML inside the PHP script allows very
quick changes. I don't have to search for the opening and closing tags buried inside the
HTML as in Listing 20.5. It also allows me to break code up into separate lines in the
source code that appear as a single line in the output. An example is the header text. I can
enhance the readability but not sacrifice the presentation. This has become very handy
when dealing with tables. Leaving any whitespace between a TD tag and an image causes
an extra pixel to appear. In an HTML file, the solution is to run the whole thing together
on one line. Inside a PHP script I can have many print calls and send an endline only
in the last. The result is a single line in the output, but very readable source code.
The usefulness of these techniques, like that of many others, increases with the size of the
project. I've created 50-page Web applications using both approaches and can attest to the
value of putting everything inside the PHP code.
Listing 20.5 Mixing PHP and HTML
$Hour = date("H");
$Intensity = round(($Hour/24.0)*(0xFF));
$PageColor = dechex($Intensity).
dechex($Intensity).
dechex($Intensity);
?>