demosthenes.info

A blog by Dudley Storey on , , , , , , and anything else that strikes his fancy.

featured articles

popular favourites

PHP echo

PHP is often used to generate small “snippets” of content, often through the echo function. Just where and how echo is used is a matter of both efficiency and (to a lesser degree) personal style.

One option is to echo both the content and the HTML surrounding it:

  1. <?php echo '<p>Some dynamic content here</p>' ?>

...or you could place the HTML code outside the PHP, which is usually my preferred solution, especially when combined with a PHP shortcut for echo:

  1. <p><?='Some dynamic content here'?></p>

Neither approach is “wrong”: your chosen solution depends on which one is more efficient.

There is one final consideration we might make. PHP runs without any awareness of the HTML code before or after it; because of that, the code it generates, while perfectly valid, may not be formatted terribly well when you use "View Source" in your browser. If this is important to you, use "escape characters" in your code:

  1. <?php echo '<p>Test content here</p>\n' ?>

That \n forces PHP to create a new line after it executes, making your code more readable. Escapes may also be used before characters that might otherwise be interpreted incorrectly: for example, if in the above line, it we wanted to say “Test text's here” we would alter our PHP code to:

  1. <?php echo '<p>Test text\'s here</p>\n' ?>

In this case the backwards slash character tells PHP that that apostrophe is “real” and is not a single quote that will terminate our code prematurely.

Interweaving PHP, HTML and CSS is a very powerful technique, but you must be clear on where each begins and ends in order to produce a whole, complete and valid page.

web developer guide

featured comment

by JoelB in Goodbye, JQuery Validation: HTML5 Form Errors With CSS3

what i'm reading

A Storm of Swords: A Song of Ice and Fire: Book Three
A Storm of Swords: A Song of Ice and Fire: Book Three

what i'm watching

Californication: The Third Season
Californication: The Third Season

what i'm playing

Mass Effect 3 Collector's Edition
Mass Effect 3 Collector's Edition

what i'm hearing

Dub FX
Dub FX

blogs

podcasts

no ads ever

This blog is free of advertising, and always will be.

creative commons licensed

The content of this blog is free to use in whatever way you wish under the Creative Commons license.