How can I echo HTML in PHP?
Solution 1
There are a few ways to echo HTML in PHP.
1. In between PHP tags
<?php if(condition){ ?>
<!-- HTML here -->
<?php } ?>
2. In an echo
if(condition){
echo "HTML here";
}
With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:
echo '<input type="text">';
Or you can escape them like so:
echo "<input type=\"text\">";
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.
NOTE: PHP short tags <?
and ?>
are discouraged because they are only available if enabled with short_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.
Solution 2
Try it like this (heredoc syntax):
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
echo $variable;
Solution 3
You could use the alternative syntax alternative syntax for control structures and break out of PHP:
<?php if ($something): ?>
<some /> <tags /> <etc />
<?=$shortButControversialWayOfPrintingAVariable ?>
<?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
<!-- else -->
<?php endif; ?>
Solution 4
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?>
instead of <?=$var?>
depending on your PHP setup.
Solution 5
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
Robin Rodricks
Updated on July 27, 2020Comments
-
Robin Rodricks almost 4 years
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";
-
Frank V almost 15 years@Jeremy: This is probably the best, most direct way assuming you are not looking for something more... Are you looking for something more?
-
Robin Rodricks almost 15 yearsYes, specifically the ability to use PHP comments in between the HTML, comments that will not be echo'd.
-
Robin Rodricks almost 15 yearsAre ASP tags compatible with PHP 4+?
-
Greg almost 15 yearsYes but get em while they last - they're being removed from PHP (not sure which version... if they haven't gone already)
-
Jeremy Logan almost 15 yearsShouldn't the "/* HTML here */" REALLY be a "<!-- HTML here -->" ? ;)
-
Chris Bier almost 15 yearsYes on the first post you are correct. I was caught up in the code haha. Thank you.
-
lfx over 12 years@MhdSyrwan just random chars, you can read more here php.net/manual/en/…
-
Ayush Mishra over 11 yearsThanks, @Chris B. it helped me. With echos, if you wish to use double quotes in your HTML you must use single quote echos like so: I was actually missing this.
-
mcon over 8 yearsThis first link in the answer is now removed :(
-
igorsantos07 over 8 yearsActually, the only short tags available from 5.4 onwards are the short echo tags
<?=$var?>
. Short tags are discouraged as usual, and are to be removed (<? doStuff() ?>
). -
TheCuBeMan over 8 yearsAnd, if you're looking for a way to print out something in the code from within a controller file (in MVC working), like I did and got me here, then you need to use "var_dump(myvar)" instead of "echo myvar".
-
Caltor over 7 yearsCould somebody expand the Heredocs section of this answer pls.
-
Chris Bier over 7 yearsI will try to update it soon. In the meantime, you can look at the PHP docs for more info on the heredoc syntax: php.net/manual/en/language.types.string.php
-
Julix about 7 yearscare to elaborate? I don't see the opening or closing PHP brackets, but both HTML and PHP, so huh? - the link works and answers it better, but maybe it should be in the answer text then, not in the comments?
-
Fahmi over 6 years@Julix of course you need to add opening and (depends) closing PHP tags. He just wanted to make the example short.
-
Julix over 6 yearsI got it; somehow I missed this was heredocs syntax (i.e. the entire code is php). I got confused, since I was new to PHP at the time and used to seeing syntax like
<?php $variable = "bla"; ?> <html> <body class="<?php echo $variable ?>"> </body> </html>
--- So I thought a bunch of brackets were missing and was unsure where exactly they'd go. It's always funny when my slightly older comments get answered, since I was so very new to it all then. -
A Friend almost 4 yearsNot sure why your answer was specifically down-voted when someone wrote an almost identical answer in this same thread and got 30 upvotes. This is completely valid syntax though. Stack overflow makes no sense sometimes...
-
Rocky Kev over 3 yearsI agree. It could be that
($contition == true)
is frowned upon. Preferrably, you would instead do($contition)
(sic) -
Rocky Kev over 3 yearsThat's a very opinionated take. You can totally echo out HTML without issues.
-
miken32 almost 3 years@AFriend it could be that, as you point out, the same answer was posted a decade before this one, and was accepted by the OP, and this adds nothing to it.