Page 1 of 1
Should i use echo to construct HTML?
Posted: Thu Jan 07, 2010 10:58 am
by Lureren
Hi
I have a simple question about using echo/print. Should i use echo/print to construct HTML-code?
E.g.:
Code: Select all
$name = $_GET[name];
echo "<p>" . $name . "</p>";
Code: Select all
$name = $_GET[name];
<p><?php echo $name; ?></p>
Which is best, and why?
Re: Should i use echo to construct HTML?
Posted: Thu Jan 07, 2010 11:01 am
by AbraCadaver
It is really personal preference, but the trend is and what seems to be more maintainable is to separate display and logic. So what is commonly done is to do PHP logic related stuff and then include a file that is mostly HTML but has some echos in it as in your second example. This also makes it easier for developers and designers to work together as the files for display are not littered with loops, db queries etc...
Re: Should i use echo to construct HTML?
Posted: Thu Jan 07, 2010 6:58 pm
by Griven
Like AbraCadaver said, it's a personal preference. I use both methods in my projects whenever they seem appropriate.
For example, when I need to use a short bit of HTML in my code, I'll just echo it like so:
Code: Select all
//Lots of PHP
echo '<p>A short bit of HTML</p>';
//Lots of PHP
However, if the block of HTML is large, I'll escape PHP and just use pure HTML.
Code: Select all
//Some PHP
?>
<p>Just pretend this is a crapload of HTML</p>
<?php
//Some more PHP
Re: Should i use echo to construct HTML?
Posted: Fri Jan 08, 2010 4:40 am
by timWebUK
Someone on this forum showed me a heredoc. That was quite useful for outputting large amounts of HTML (that contained a lot of PHP variables)
Code: Select all
$hello = <<<HELLO
<b>$myVar</b>
<b>$myVar</b>
<b>$myVar</b>
<b>$myVar</b>
<b>$myVar</b>
<b>$myVar</b>
HELLO;
You then would echo $hello where you needed it. It can also be used to keep code quite tidy I find. Sometimes you have a lot of HTML and a lot of PHP variables and it just is far too long winded to go around opening and closing PHP I think.
Manual:
heredoc
Re: Should i use echo to construct HTML?
Posted: Fri Jan 08, 2010 3:13 pm
by pickle
I try to follow your second example as much as possible. I don't like having my output in multiple places & it keeps my PHP code & HTML code readable.