| [ Team LiB ] |
|
26.2 Using PHP to Output All HTMLAny 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 function sends 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. Compare the simple examples in Listing 26.5 to Listing 26.6. Both change the background color of the page depending on the time of day. Listing 26.5 Mixing PHP and HTML
<html>
<head>
<title>Listing 26-5</title>
</head>
<?php
$Hour = date("H");
$Intensity = round(($Hour/24.0)*(0xFF));
$PageColor = dechex($Intensity) .
dechex($Intensity) .
dechex($Intensity);
?>
<body bgcolor="#<?php print($PageColor); ?>">
<h1>Listing 26-5</h1>
</body>
</html>
Listing 26.6 Converting script to be completely PHP
<?php
//start document
print("<html>\n");
print("<head>\n");
print("<title>Listing 26-6</title>\n");
print("</head>\n");
$Hour = date("H");
$Intensity = round(($Hour/24.0)*(0xFF));
$PageColor = dechex($Intensity) .
dechex($Intensity) .
dechex($Intensity);
//show body
print("<body bgcolor=\"#$PageColor\">\n");
print("<h1>Listing 26-6</h1>\n");
print("</body>\n");
print("</html>\n");
?>
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 26.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. |
| [ Team LiB ] |
|