Chapter 5. Basic syntax

Table of Contents
Escaping from HTML
Instruction separation
Comments

Escaping from HTML

When PHP starts to handle file, it will just output the text it encouters. So if you have a HTML-file, and you change its extension to .php, your file will keep working.

If you want to insert php-statements at some point in your file, you'll need to indicate so to php, by entering "PHP mode" in either of the following ways:

Example 5-1. Ways of escaping from HTML


1.  <? echo ("this is the simplest, an SGML processing instruction\n"); ?>
    <?= expression ?>  This is a shortcut for "<? echo expression ?>"
    
2.  <?php echo("if you want to serve XHTML or XML documents, do like this\n"); ?>

3.  <script language="php"> 
        echo ("some editors (like FrontPage) don't
              like processing instructions");
    </script>

4.  <% echo ("You may optionally use ASP-style tags"); %>
    <%= $variable; # This is a shortcut for "<%echo .." %>
      

The first way is only available if short tags have been enabled. This can be done by enabling the short_open_tag configuration setting in the PHP config file, or by compiling PHP with the --enable-short-tags option to configure.

The second way is the generally preferred method, as it allows for the next generation of XHTML to be easily implemented with PHP.

The fourth way is only available if ASP-style tags have been enabled using the asp_tags configuration setting.

Note: Support for ASP-style tags was added in 3.0.4.

The closing tag for the block will include the immediately trailing newline if one is present.

PHP allows you to use structures like this:

Example 5-2. Advanced escaping


<?php

if ( boolean-expression )
{
    ?>
<strong>This is true.</strong>
    <?php
}
else
{
    ?>
<strong>This is false.</strong>
    <?php
}
    ?>
     
This works as expected, because PHP handles text within ?> and <?php as an echo() statement.