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 lik
In addition to Chris B's answer, if you need to use echo
anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>
's, you can use the syntax below.
For example you want to display the images of a gallery:
foreach($images as $image)
{
echo
'<li>',
'<a href="', site_url(), 'images/', $image['name'], '">',
'<img ',
'class="image" ',
'title="', $image['title'], '" ',
'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
'alt="', $image['description'], '"',
'>',
'</a>',
'</li>';
}
Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo
with parameters is more effective than concatenating.
Try this:
<?php
echo <<<HTML
Your HTML tags here
HTML;
?>
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';
echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
echo '
<html>
<body>
</body>
</html>
';
or
echo "<html>\n<body>\n</body>\n</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.)
$page = 'Hello, World!';
$content = file_get_contents('html/welcome.html');
$pagecontent = str_replace('[[content]]', $content, $page);
echo($pagecontent);
Alternatively, you can just output all the PHP stuff to the screen captured in a buffer, write the HTML, and put the PHP output back into the page.
It might seem strange to write the PHP out, catch it, and then write it again, but it does mean that you can do all kinds of formatting stuff (heredoc, etc.), and test it outputs correctly without the hassle of the page template getting in the way. (The Joomla CMS does it this way, BTW.)
I.e.:
<?php
ob_start();
echo('Hello, World!');
$php_output = ob_get_contents();
ob_end_clean();
?>
<h1>My Template page says</h1>
<?php
echo($php_output);
?>
<hr>
Template footer
I am partial to this style:
<html>
<head>
<% if (X)
{
%> <title>Definitely X</title>
<% }
else
{
%> <title>Totally not X</title>
<% }
%> </head>
</html>
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.