Class 7 – The XML declaration in your XHTML code can cause problems if your server has PHP short tags enabled

Posted: April 11th, 2010 | Author: | Filed under: php | Tags: | No Comments »

One potential problem that you may come across when putting XHTML code inside your PHP files is that the XML declaration tag may confuse the PHP server.

Short tags

Some PHP servers, including ours, are set up to accept “short tags”, which are shortcut versions of some PHP commands.  For example, on our server, you can either open your PHP script by writing

<?php

Or you can simplify that to

<?

This is a shortcut, “short tag” version of the opening PHP tag that allows lazy developers to type less.

There is another short tag that replaces the normal “echo” command.  For example, a normal echo might look like

<?php echo "arugala"; ?>

And the shortened version of the same command would be

<?= "arugala"; ?>

The problem

A problem arises when we put XHTML code inside a PHP file (a file with the .php extension) because the “xml” tag that we use as the first line of our “bare minimum” XHTML document includes the “<?” in it.

<?xml version="1.0" encoding="utf-8"?>

This confuses the PHP processor, which thinks you intend to use a PHP short tag, which you do not.  You will an error message about a “parse error”.

See this problem in action

The solution

The solution is to encapsulate the “<?” characters inside of a PHP echo statement.  This way you prevent the PHP processor from thinking that those two characters are the start of a PHP opening tag.

<?php echo "<?"; ?>xml version="1.0" encoding="utf-8"?>

See this solution in action

Why you should use PHP short tags

You may be tempted to use PHP short tags.  The conventional wisdom is that it’s a bad idea.  This is because not all servers are set up to support them.

So if you at some point move your code from a server that does support them to a server that doesn’t, your code will cease to work.

This does not fit in with our philosophy of writing code using only those practices that are guaranteed to work with a minimum of fuss.

Related posts:

  1. Class 8 – Uploading Files to Server in PHP


Leave a Reply