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?
They are both used to output data to the screen. The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print .
Using echo or print: PHP echo or print can be used to display HTML markup, javascript, text or variables.
PHP echo statement can be used to print the string, multi-line strings, escaping characters, variable, array, etc. Some important points that you must know about the echo statement are: echo is a statement, which is used to display the output. echo can be used with or without parentheses: echo(), and echo.
You should use readfile() : readfile("/path/to/file"); This will read the file and send it to the browser in one command.
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With