Separating PHP from HTML

Very often PHP coders will output HTML like so:

<?php
print '<ul>'; 
foreach( $links as $link=>$title ){
    print '<li><a href="'.$link.'">'.$title.'</a></li>';
}
print '</ul>';
?>
 

This causes the following issues:

It's harder for web designers to work with
Tthe code won't display properly in dreamweaver design mode. And designers will need some knowledge of PHP and good knowledge of HTML to be able to edit it.

It gets in the way of syntax highlighting
Syntax highlighters will just highlight the printed line as one big string. They will not be able to highlight the different tags and attributes. So the code is much harder to read.

It gets in the way of code-assist
Code assist or intellisense won't be able to help you with your HTML because it will be treating the code as a string much like with syntax highlighting.

You have to watch out for quotes.
Any singe quotes will need to be escaped like so \' . This can be time consuming if you are dealing with lots of text and it's also something that most web designers who are working with your code won't be aware of.

So what's the answer. Well here's how I do it.

<ul>
<?
foreach( $links as $link=>$title ){
?>
    <li><a href="<?=$link;?>"><?=$title;?></a></li>
<?
}
?>
</ul>

This approach involves a few more PHP tags but it solves all of the above issues. It works better in IDEs, is easier to read and maintain and helps keep PHP and HTML separate.



06/06/2009 permalink | Posted in web development | 3 Comments »
Short tags are a great way of making PHP mixed with HTML easier to read.

Going one step further, a Model View Controller (MVC) system completely separates the design elements (i.e. your HTML with a sprinkling of PHP) from the rest of your application.

Designers can then hack away at the HTML without having to get their hands too dirty with the PHP.

There are numerous other advantages of using MVC - Zend Framework has this functionality built in, as do a number of other PHP frameworks.
Steve Hollis on 14/07/2009

Leave a reply

Name
Email (not published)
Website


Bookmark and Share

About me

Adam Jimenez is a freelance web developer who has been professionally developing websites since 2000.

Find me


Projects


Archive


Email updates

Email
Email Marketing by ShiftMail