| [ Team LiB ] |
|
26.3 Separating HTML from PHPThe last approach I want to discuss involves using the include and require functions. As you may recall from Chapter 7, these functions include a file in the PHP code. The file is considered to be a PHP file regardless of the extension on the name. If PHP code appears in the included file, it is surrounded by <?php and ?> tags. You may want to turn back to the functional reference to refresh yourself on the differences between include and require, but they aren't particularly important to this discussion. Certain chunks of HTML must appear on every well-formed page. Additionally, you may develop repeating elements such as a company logo. Rather than write them into every page, you may choose to put them into a file and dynamically include them. Listing 26.7 contains HTML you might include at the top of every page on a site. In Listing 26.8 are two lines to close a page. Listing 26.10 wraps the content in Listing 26.9 with the opening and closing code to form a complete page. Listing 26.7 Start of HTML page<html> <head> <title>PHP</title> </head> <body> Listing 26.8 End of HTML page</body> </html> Listing 26.9 Page content<p> This is the body of the page. It's just a bit of HTML. </p> Listing 26.10 Page-building script
<?php
// include code to open HTML page
require("26-7");
// include content
require("26-9");
// include code to close HTML page
require("26-8");
?>
In this way, HTML and PHP are separated into modules. In this example, I have hardcoded the inclusion of a two-line HTML file, but I could just as easily have included the color tables from Listing 26.2. The HTML in Listing 26.7 can be reused from page to page, and if I need to add something to every page on the site, I need to edit only that one file. I might want to add the PHP function from Listing 26.1. It will then be available for use inside the code from Listing 26.9. It may occur to you that this approach is exhibiting another pattern. Every page on the site will simply become three calls to require. The first and last calls will always be the same. In fact, every page on the site will vary simply by the name of the file included in the second require statement. This takes us beyond the issue of integrating HTML and PHP and into the structural design of a site. It is possible to create a site that has exactly one PHP script. This idea is developed in Chapter 27. |
| [ Team LiB ] |
|