Generating HTML with PHP

The PHP scripting language can be used to generate dynamic HTML pages. The PHP interpreter executes instructions between the delimiters <?php and ?>. The PHP header() function can be used to set HTTP headers in the response.

Any HTML code between a ?> delimiter and the next <? is sent verbatim. Since that last delimiter indicates the start of PHP instructions, it cannot appear in the code, so any tags starting with <? must be sent using PHP instructions. Here are some examples of these tags and how the PHP echo instruction can be used to solve this issue:

the <?xml?> declaration
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
processing instructions
echo '<?xml-stylesheet type="text/xsl" href="site-wide-templates.xsl"?>'."\n"; 

PHP can also escape from HTML and echo an expression using <?='...'?>, but only if the short_open_tag configuration setting is turned on.

Use the PHP header function to generate the proper HTTP headers for HTML 5
Use the PHP echo function to generate the proper HTML 5 declarations

If you simply copy the PHP script below and then enter the URL that executes the script in the W3C Markup Validation Service, the HTML code that it generates will validate successfully. Therefore this can be used as a starting template for generating a valid HTML document from PHP.

<?php

session_start();
header('Content-Type: application/xhtml+xml; charset=utf-8');
header('Content-Disposition: inline; filename="index.html"');

echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
echo '<?xml-stylesheet type="text/xsl" href="/site-wide-templates.xsl"?>'."\n";

?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>My HTML Title</title>
 </head>
 <body>
 </body>
</html>

Uncomment the echo line for the xml-stylesheet instruction if you use templates for common visual elements such as navigation areas.

For more information, see PHP Dynamic HTML Generation at Code Design Patterns.