Using PHP to Output All HTML PHP

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 PHPpowered: 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. 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. 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.

Mixing PHP and HTML

<HTML>
<HEAD>
<TITLE>Listing /TITLE>
</HEAD>
<?
$Hour = date("H");
$Intensity = round(($Hour/24.0)*(0xFF));
$PageColor = dechex($Intensity) .
dechex($Intensity) .
dechex($Intensity);
?>
<BODY BGCOLOR="#? print($PageColor); ?>">
<H1>Listing </H1>
</BODY>
</HTML>

Converting Script to Be Completely PHP

<?
print("<HTML>n");
print("<HEAD>n");
print("<TITLE>Listing 20.6</TITLE>n");
print("</HEAD>n");
$Hour = date("H");
$Intensity = round(($Hour/24.0)*(0xFF));
$PageColor = dechex($Intensity) .
dechex($Intensity) .
dechex($Intensity);
print("<BODY BGCOLOR="#$PageColor">n");
print("<H1>Listing 20.6</H1>n");
print("</BODY>n");
print("</HTML>n");
?>

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics