I’ve been using PHP seriously for a while now, and overall I think it’s the most productive programming language I’ve ever encountered. However, one of the things, as a PHP programmer, you need to do on a regular basis is to output HTML to the browser in order to draw web pages.
The problem is that HTML uses the ” (quote) character and so does PHP so, if you want to use a bit of HTML like this:
<p class=”indentedbody”>Here is some text.</p>
you need to handle them specially in PHP.
The simplest way is:
<?php echo(“<p class=’indentedbody’>Here is some text.</p>”);?>
…in other words to replace quotes with single quotes. The main disadvantage is that it means if you want to use a variable in the html (eg to replace the “Here is some text”) you need to concatenate (glue) them together like this:
<?php
$thetext=”Here is some text”;
echo “<p class=’indentedbody’>”.$thetext.”</p>”;
?>
…note the “.” character which concatenates strings. It may not look like too much of a problem but the more variables that need to be inserted, the messier and harder to understand it becomes.
Another option is to “escape” the html quotes like this:
<?php
$thetext=”Here is some text”;
echo “<p class=\”indentedbody\”>$thetext</p>”;
?>
..so the \ has been used to tell PHP that the ” is a literal quote, not the end of a string of characters. Again, this works for small blocks of text but is a major pain in the backside for complex HTML. I’ve worked around this in the past by doing a “search and replace” in my programming environment, swapping all ” characters for \” pairs.
But there’s an easier way and it’s been around for ages. It’s just that almost no-one uses it. Here it is
<?php
$thetext=”Here is some text”;
echo <<<MYHTML
<p class=”indentedbody”>$thetext</p>
MYHTML;
?>
Bascially, what’s going on is that the string “MYHTML” replaces the quotes as the delimiter: in other words, instead of putting ” at the start and end, we put MYHTML. This means that, as long as we don’t use the characters “MYHTML” within the string, we can use double quotes as we like so the whole thing is much more readable and easy to edit.
The heredoc syntax as applied to PHP is a bit fussy so check the manual but this is going to be a major timesaver for anyone using either of the other two techniques.


.gif)