|
|
 |
Chapter 10. Basic syntax
When PHP parses a file, it looks for opening and closing tags,
which tell PHP to start and stop interpreting the code between
them. Parsing in this manner allows php to be embedded in all
sorts of different documents, as everything outside of a pair
of opening and closing tags is ignored by the PHP parser.
Most of the time you will see php embedded in HTML documents,
as in this example.
You can also use more advanced structures:
Example 10-1. Advanced escaping |
<?php
if ($expression) {
?>
<strong>This is true.</strong>
<?php
} else {
?>
<strong>This is false.</strong>
<?php
}
?>
|
|
This works as expected, because when PHP hits the ?> closing
tags, it simply starts outputting whatever it finds until it hits
another opening tag. The example given here is contrived, of
course, but for outputting large blocks of text, dropping out of
PHP parsing mode is generally more efficient than sending all of
the text through echo() or
print().
There are four different pairs of opening and closing tags
which can be used in php. Two of those, <?php ?> and
<script language="php"> </script>, are always available.
The other two are short tags and ASP
style tags, and can be turned on and off from the php.ini
configuration file. As such, while some people find short tags
and ASP style tags convenient, they
are less portable, and generally not recommended.
Note:
Also note that if you are embedding PHP within XML or XHTML
you will need to use the <?php ?> tags to remain
compliant with standards.
Example 10-2. PHP Opening and Closing Tags |
1. <?php echo 'if you want to serve XHTML or XML documents, do like this'; ?>
2. <script language="php">
echo 'some editors (like FrontPage) don\'t
like processing instructions';
</script>
3. <? echo 'this is the simplest, an SGML processing instruction'; ?>
<?= expression ?> This is a shortcut for "<? echo expression ?>"
4. <% echo 'You may optionally use ASP-style tags'; %>
<%= $variable; # This is a shortcut for "<% echo . . ." %>
|
|
While the tags seen in examples one and two are both
always available, example one is the most commonly
used, and recommended, of the two.
Short tags (example three) are only available when they are
enabled via the short_open_tag
php.ini configuration file directive, or if php was configured
with the --enable-short-tags option.
Note:
If you are using PHP 3 you may also enable short tags via
the short_tags() function. This
is only available in PHP 3!
ASP style tags (example four) are only available when
they are enabled via the asp_tags php.ini
configuration file directive.
Note:
Support for ASP tags was added in 3.0.4.
Note:
Using short tags should be avoided when developing applications
or libraries that are meant for redistribution, or deployment on
PHP servers which are not under your control, because short tags
may not be supported on the target server. For portable,
redistributable code, be sure not to use short tags.
User Contributed Notes
Basic syntax
p o r g e s at the gmail dot com server
01-Apr-2005 11:02
mike at skew dot org, I believe the differentiation is that "x"-"m"-"l" as a PI target is explicitly excluded from the definition of processing instructions.
jasperbg at gmail dot com
31-Mar-2005 06:38
To mwild at iee dot NO_SP_AM dot org, there is *no need* to escape <script language="php"> blocks as CDATA in an XHTML document! These scripts are parsed at the server so no validator ever sees them, unless something is wrong with your server config!
To all doing weird and wonderful things to output XML declarations -- I just turn off short_open_tag in my .htaccess (or apache.conf if you have your own server) and output it normally, e.g.
<?xml version="1.0" encoding="UTF-8"?>
<?php
...some code...
?>
Works fine, because PHP won't try to interpret the <?xml because short_open_tag is off.
Lachlan Hunt
29-Mar-2005 12:06
The person that suggested the use of this meta element above is wrong:
<meta http-equiv="Content-Type" content="application/xml+xhtml; charset=UTF-8" />
That meta element and the XML declaration serve completely different purposes, and that meta element should not be used. Such information should be set using the HTTP Content-Type header (see the header() function).
Any XHTML page that just uses that meta element without proper HTTP Content-Type header, will be processed as text/html by browsers regardless, and when the HTTP headers do serve as application/xhtml+xml (or other XML MIME type), that charset parameter in the meta element will be ignored.
mike at skew dot org
21-Oct-2004 07:53
mart3862 mentions "XML processing instructions" and quotes their syntax from the spec, but is mistaken in using
<?xml version="1.0" ...?>
as an example. This little bit of markup that appears at the beginning of an XML file is in fact not a processing instruction at all; it is an "XML declaration" -- or, if it appears in an entity other than the main document, a "text declaration". All three constructs are formatted slightly differently, although they all do begin and end with the same.
The difference between a processing instruction, an XML declaration, or a text declaration is more than just a matter of subtle differences in syntax, though. A processing instruction embodies exactly two opaque, author-defined pieces of information (a 'target' and an 'instruction') that are considered to be part of the document's logical structure and that are thus made available to an application by the XML parser. An XML or text declaration, on the other hand, contains one to three specific pieces of information (version, encoding, standalone status), each with a well-defined meaning. This info provides cues to the parser to help it know how to read the file; it is not considered part of the document's logical structure and is not made available to the application.
stooges_cubed at racerx dot net
20-Oct-2004 04:13
In the note above about escaping XML/PHP style <?xml tags, the following code was used:
<?php echo <<<EOD
<?xml version="1.0"?>
...all sorts of XML goes here...
Nothing will affect the output of this code until:
EOD;
?>
EOD is just an example stop/start name.
This works too:
<?php $myOutput = <<<MYHTMLSAFEOUTPUT
<?xml version="1.0"?>
<html>
<title>PHP Example</title>
<body>
<p>...all sorts goes here...</p>
</body>
</html>
MYHTMLSAFEOUTPUT;
echo $myOutput;
?>
Only disadvantage of using this is that all the code highlighting programs I've seen never get it right, making your code look eronous in the majority of viewers.
Another alternative is to keep the XML / HTML in a separate include file and read in when needed. I don't know how efficient/inefficient this is for (idiots like yourselves) small amounts of text.
xmlheader.txt:
<?xml version="1.0"?>
mypage.php:
<?php
include("xmlheader.txt");
?>
crtrue at coastal dot edu
01-May-2004 02:02
Although you can use the above methods to pass a document off as a valid for the W3C parser, a simpler-and-perfectly-legal method of doing so is to simple declare the document type in a meta tag. Something along these lines (mind the values in 'content' - I haven't personally used the Content-Type method in awhile):
<meta http-equiv="Content-Type" content="application/xml+xhtml; charset=UTF-8" />
Of course if you're using just XML, and don't use such functions, then the above methods will work just as fine.
mart3862 at yahoo dot com dot au
18-Apr-2004 12:29
Now the ultimate truth on how you should output xml processing instructions:
There have been several posts suggesting ways to include the text <?xml version="1.0" encoding="utf-8"?> in your output when short_tags is turned on, but only the following should be used:
<?php echo '<?xml version="1.0" ?'.'>' ?>
or
<?php echo "<?xml version=\"1.0\"\x3F>" ?>
Using one of these methods, and not making use of short tags, means your source code will also be a valid XML document, which allows you to do many things with it such as validation, XSLT translations, etc, as well as allowing your text editor to parse your code for syntax colouring. Every PHP tag will simply be interpreted as an XML processing instruction (commonly referred to as PI).
The reason why all the other suggested methods are not advisable is because they contain the characters ?> inside the PHP tag, which the XML parser will interpret as the end of the processing instruction.
A processing instruction is defined in XML as:
PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
In other words, it explicitly forbids the characters ?> to occur together within a processing instruction, unless they are delimiting the end of the tag. It also requires a PITarget (an identifier starting with a letter) immediately after the initial start delimiter, which means that all short tag formats are also invalid XML.
Following these guidelines will result in code that is portable to servers with any configuration and allow you perform many useful tasks on your XML or XHTML source documents. Even if you do not intend to validate or translate your source documents, and you can ignore some incorrect syntax colouring in your text editor, it is still best to get into good habits early.
george at whiffen dot net
26-Feb-2004 10:12
Tip: New lines immediately following a close tag, (?>,</script>) are suppressed in the output.
For example:
Contact:-
Name:<?= $myname?>
Telephone: <?= $myphone?>
will typically produce:
Contact:-
Name: My NameTelephone: My Phone
To get the new line back, just add anything after the close tag and before the new line. A single space character works fine.
Anon
21-Feb-2004 09:05
Yet another way of adding the XML processing instruction is to use:
<?php echo '<?xml version="1.0" ?'.'>' ?>
Because the ? and > are separated, the parser will not terminate before it is supposed to.
As a side note, the W3C's parser seems to recognise this method (assuming it even checks for the PI).
TarquinWJ
06-Feb-2004 09:54
Not spotted any messages like this one - delete it if there was one.
My hosting service allows <? and ?>, but I like to use valid XHTML, so I came up with this simple solution:
It is possible to use the short tags <? ?> with XHTML or XML documents. The only problem is that X(HT)ML requires a declaration using <? and ?>
<?xml version="1.0" encoding="UTF-8"?>
To avoid the problem, simply replace <? with <<? ?>?
and ?> with ?<? ?>>
<<? ?>?xml version="1.0" encoding="UTF-8"?<? ?>>
This inserts a blank piece of PHP in between the < and ?, and when parsed will output the regular tag
<?xml version="1.0" encoding="UTF-8"?>
mwild at iee dot NO_SP_AM dot org
19-Dec-2003 08:12
The text between <script> and </script> in XHTML is PCDATA, so < and & characters in it should be interpreted as markup. This is a bit limiting for PHP, which is often used to output tags, though you can of course use < and & instead. To avoid that, which makes your code look peculiar and is easy to forget to do, you can mark the PHP as CDATA, eg :
<script language="PHP">
echo('Today is <b>'.date('l F jS').'</b>');
</script>
If you don't do this, and your code contains < or &, it should be rejected by an XHTML validator.
johnbeech at (not saying) mkv25 dot net
07-Dec-2003 07:42
In the note above about escaping XML/PHP style <?xml tags, the following code was used:
<?php echo <<<EOD
<?xml version="1.0"?>
...all sorts of XML goes here...
Nothing will affect the output of this code until:
EOD;
?>
EOD is just an example stop/start name.
This works too:
<?php // Html safe containers
$myOutput = <<<MYHTMLSAFEOUTPUT
<?xml version="1.0"?>
<html>
<title>PHP Example</title>
<body>
<p>...all sorts goes here...</p>
</body>
</html>
MYHTMLSAFEOUTPUT;
echo $myOutput;
?>
Only disadvantage of using this is that all the code highlighting programs I've seen never get it right, making your code look eronous in the majority of viewers.
Another alternative is to keep the XML / HTML in a separate include file and read in when needed. I don't know how efficient/inefficient this is for small amounts of text.
xmlheader.txt:
<?xml version="1.0"?>
mypage.php:
<?php
include("xmlheader.txt");
?>
de \ kibo \ niels
19-Dec-2002 09:19
A follow-up to the first posting on this page: If you're writing PHP code on a non-UNIX system like MacOS (and even on a UNIX system like Mac OS X!), be very careful about line breaks.
Although this was apparently fixed in 4.0.5, I got the weirdest errors while testing PHP scripts that I wrote in BBEdit (6.5) on MacOS X (10.2, running Apache 1.3.27 with PHP 4.1.2).
The Mac-style line breaks (\r) that BBEdit usually produces by default confuse the PHP parser, and it will report the strangest parse errors. (I even got errors in lines of code that were commented out! This drove me nuts for days).
Your documents have to use UNIX-style linebreaks (\n) to prevent these errors. It's advisable to configure BBEdit to produce UNIX line breaks by default in every new document (preferences!).
This problem possibly also occurs with DOS/Win systems whose linebreaks are \r\n.
dave at [nospam] dot netready dot biz
18-Mar-2002 07:21
A little "feature" of PHP I've discovered is that the <?PHP token requires a space after it whereas after the <? and <% tokens a space is optional.
The error message you get if you miss the space is not too helpful so be warned!
(These examples only give a warning with error_reporting(E_ALL) )
<?PHP?> fails...
<??> works...
mrtidy at mail dot com
12-Dec-2001 03:36
[Ed Note:
This is because of short_tags, <?xml turns php parsing on, because of the <?.
--irc-html@php.net]
I am moving my site to XHTML and I ran into trouble with the <?xml ?> interfering with the <?php ?> method of escaping for HTML. A quick check of the mailing list confirmed that the current preferred method to cleanly output the <?xml ?> line is to echo it:<br>
<?php echo("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); ?>
| |