Possible Duplicate:
Easiest way to echo HTML in PHP?
Hello,
one simple and short question. If you have a php file that contains HTML code, is it better to do the output with echo or to write the HTML code directly into the file? For example the file some.php contains either:
<div>This is a text</div><a href="www.example.开发者_运维百科com">test</a><?php if(---) { whatever; } ?>
or:
<?php echo "<div>This is a text</div><a href=\"www.example.com\">test</a>"; if(---) { whatever; } ?>
Which version is faster, cleaner and better?
In my opinion this really depends on how long the code snippet is. For simple lines I'd just use echo. For longer parts (especially with lots of " to escape) i'd prefer "closing" the php code (your second approach).
Depending on the amount of text/HTML to print I'd also consider using some kind of simple templating engine to load a template file and just fill in dynamic variables/placeholders/gaps.
I prefer the first method meaning HTML shouldn't be mixed with PHP as much as possible. With this I don't have to worry about mis-match of quotes, etc. There exists heredocs syntax but yet the first method is something I find easier to work with.
Just choose a way you are more comfortable with and that makes it easier for other programmers to handle you code if they have to :)
Your question seems to imply that you keep your PHP and HTML in the same file. You might want to think about separating the two. This would leave you with an HTML template that would look like your first example.
Not only will this make it easier to focus on either PHP or HTML, but like lonesomeday mentioned you will be able to leverage your IDE's HTML handling capabilities which can make things a lot easier for you. Plus it's easier to let web designers work on the frontend without them having to understand PHP.
Please rewrite:
<?php
echo '<div>This is a text</div><a href="www.example.com">test</a>';
if(---) { whatever; }
?>
The single quote parses faster then the double quotes. Second, I have heard that the opening and closing of PHP blocks would be a performance penalty, but I can't confirm that.
It is just a personal preference. I like it to echo all the HTML with PHP.
精彩评论