tags:

views:

39

answers:

2

What's the best way to create an HTML document using PHP? I find that using <?php ?> blocks becomes quite messy when the page has a lot of dynamically generated content. I was thinking about using a PHP DOM manipulation library to insert the dynamic content into "anchors" into the document. This would result in a cleaner document layout because all the PHP is in one place and the HTML is in another.

What are the readability/performance pros/cons of using PHP blocks vs using PHP DOM manipulation? What's the accepted practice of creating HTML documents with PHP?

+3  A: 

For a long time ago, I believed "anchors" were the way to go. I used the Smarty templating engine in those days. Do yourself a favor, and skip that phase. You see... soon you'll find you'll need some basic control structures in your pages. A little loop here, a small conditional there. Before you know it, you'll be implementing your own little programming language just to parse those anchors.

That's when it begins to dawn that PHP is actually a mighty fine templating language. This is the approach many frameworks these days have taken. I'd recommend taking a look at Zend Framework's Zend_View. They do a nifty little thing where they use output buffering to catch the result of a PHP page being included. This allows them interesting stuff like assigning data to an object and retrieving it using $this-> in the template.

What it boils down to is what you want to do in your pages... seperation of concerns, that is, splitting your 'presentation' from your business logic, is pretty much always a good idea. And if you restrict yourself to presentation logic, it naturally follows that your pages will contain only the PHP you really need. As mentioned above.. a while loop, a few If's. That should be it.

See also: MVC pattern

kander
I always give a little groan when I have to maintain a smarty project.
willoller
I know why, and on behalf of all developers who made this mistake: Sorry :'(
kander
+2  A: 

There are several practices to solve this:

1) A big mess of PHP and HTML together. 2) Use templates.

You have presented something I have never heard about, maybe because it's be problematic or inefficient. Let's say, it could be considered as a kind of template, but there are easier ways how to reach the goal.

Templates are a way how to separate HTML and PHP as much as it's possible. You can use big templating frameworks, e.g. Smarty, but in my opinion, it's better to keep the matter simple and use something similar to this: http://www.massassi.com/php/articles/template_engines/ I think that is the best practice widely used in the PHP world and it is also the answer for your question.

Honza Javorek
+1 for the template engine article, I love that one.
Charles