Embedding PHP in HTML

You embed PHP code into a standard HTML page. For example, here’s how you can dynamically generate the title of an HTML document:

<HTML><HEAD><TITLE><?echo $title?></TITLE></HEAD>-..

The <?echo $title?> portion of the document is replaced by the contents of the $title PHP variable. echo is a basic language statement you can use to output data.

There are a few different ways to embed your PHP code. As you just saw, you can put PHP code between <? and ?> tags:

<? echo "Hello World"; ?>

This style is the most common way to embed PHP, but it is a problem if your PHP code needs to coexist with XML, as XML may use that tagging style itself. If this is the case, you can turn off this style in the php3.ini file with the short_open_tag directive. Another way to embed PHP code is within <?php and ?> tags:

<?php echo "Hello World"; ?>

This style is always available and is recommended when your PHP code needs to be portable to many different systems. Embedding PHP within <SCRIPT> tags is another style that is always available:

<SCRIPT LANGUAGE="php" > echo "Hello World"; </SCRIPT>

One final style, where the code is between <% and %> tags, is disabled by default:

<% echo "Hello World"; %>

You can turn on this style with the asp_tags directive in your php3.ini file. The style is most useful when you are using Microsoft FrontPage or another HTML authoring tool that prefers that tag style for HTML-embedded scripts.

You can embed multiple statements by separating them with semicolons: ...

Get Webmaster in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.