I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?
echo '<html>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";
Another approach is put the HTML in a separate file and mark the area to change with a placeholder [[content]] in this case. (You can also use sprintf instead of the str_replace.)
Alternatively you can just output all the php stuff to the screen captured in a buffer, then write the html, then put the php output back into the page.
It might seem strange to write the php out, catch it, then write it again, but it does mean that you can do all kinds of formatting stuff (Heredocs etc),& test it outputs correctly without the hassle of the page template getting in the way. (Joomla CMS does it this way, BTW) ie:
try like this:
There are a few ways to echo HTML in PHP.
1. In between PHP tags
2. In an echo
With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:
Or you can escape them like so:
3. Heredocs
4. Nowdocs (as of PHP 5.3.0)
Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g.
<?=$someVariable?>
).There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g.
{{someVariable}}
).The primary benefit of using a template engine is keeping the design (Presentation Logic) separate from the coding (Business Logic). It also makes the code cleaner and easier to maintain in the long run.
If you have any more questions feel free to leave a comment. Further reading is available on these things in the PHP Documentation.
God Bless!
NOTE: PHP short tags
<?
and?>
are discouraged because they are only available if enabled withshort_open_tag
php.ini configuration file directive, or if PHP was configured with the--enable-short-tags
option. They are available, regardless of settings from 5.4 onwards.I am partial to this style:
I do use ASP-style tags, yes. The blending of PHP and HTML looks super-readable to my eyes. The trick is in getting the
<%
and%>
markers just right.Try This May Help You.......
or