Generating HTML with Server-Side Scripting

 

ATTENTION: THIS PAGE IS Valid HTML 5 AND IS BEST VIEWED WITH HTML 5 - Please upgrade your browser or download one of the HTML 5 compatible browsers such as Mozilla Firefox, Chrome, Opera or IE 9 (March 14, 2011 or later). For more information see HTML 5 browsers.


If you find this helpful, please click the Google +1 Button to the left, if it is white, to make it turn blue or red. Thank you! (It also helps find this page again more easily.)


PDF mobile

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.


Valid HTML 5