[ Team LiB ] Previous Section Next Section

Combining HTML and PHP

The code in Listing 3.1 and Listing 3.2 is pure PHP. You can incorporate this into an HTML document simply by adding HTML outside the PHP start and end tags, as shown in Listing 3.3.

Listing 3.3 A PHP Script Including HTML
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 3.2 A PHP Script Including HTML</title>
 7: </head>
 8: <body>
 9: <div><b>
10: <?php
11: print "hello world";
12: ?>
13: </b></div>
14: </body>
15: </html>


As new devices access the Web running new browsers on ever more platforms, standards are becoming increasingly important. Where possible, the output from code examples in this book now conform to Extensible Hypertext Markup Language (XHTML) standards. XHTML is an XML-based version of HTML that can be parsed and validated. Because of this, it is more accessible to lightweight browsers running on small memory devices. XHTML also helps to promote genuinely cross-browser mark-up. You can read more about XHTML at http://www.w3.org/TR/xhtml1/.

Notice that Listing 3.3 starts with a complex-looking element. This is known as the DOCTYPE declaration, and it declares the XHTML version to which the document conforms.

As you can see, incorporating HTML into a PHP document is simply a matter of typing in the code. The PHP engine ignores everything outside PHP open and close tags. If you were to view Listing 3.3 with a browser, as shown in Figure 3.3, you would see the string hello world in bold. If you were to view the document source, as shown in Figure 3.4, the listing would look like a normal HTML document.

Figure 3.3. The output of Listing 3.2 as viewed in a browser.


Figure 3.4. The output of Listing 3.2 as HTML source code.


You can include as many blocks of PHP code as you need in a single document, interspersing them with HTML as required. Although you can have multiple blocks of code in a single document, they combine to form a single script. Any variables defined in the first block usually are available to subsequent blocks.

    [ Team LiB ] Previous Section Next Section