Meta

PHP in HTML or HTML in PHP?

What’s nice about PHP (among other things) is that code blocks can easily be nested inside the HTML of a page. This way you in insert dynamic content just like that. Of course you can also go the other way and echo out HTML via PHP.

My simple rule is: When you have a clear overweight of one or the other use this as your main code and nest-in the other.

This makes source code way more readable than, for example, when you have orgies of opening and closing PHP tags inside “some” HTML tags!

Like this:

Related

Post navigation

2 thoughts on “PHP in HTML or HTML in PHP?”

I feel most people would agree that the best answer is, do whatever keeps them separate. Embedding HTML in PHP causes syntax highlighting headaches and loses readability. You also have to be wary of the PHP parser when writing/editing the HTML i.e. escaping string or variable delimiters, etc.

Good point and thanks for the feedback. A clear separation would of course be ideal. Though it’s getting a bit religious there like when it comes to the proper use of templating engines.

Personally, I agree you should separate your business logic and only feed the resulting data to the template engines or views. But to me it’s okay then to use PHP to build the HTML.
And to avoid the pitfalls in terms of string escaping, the heredoc syntax can be useful.

(I guess you wrote some code at the end of your comment. If so, it seems that WP has eaten it. Sry ’bout that, I’m looking into it).