Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it allways better to output HTML code in a php file with echo? [duplicate]

Tags:

html

php

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?

like image 815
phpheini Avatar asked Mar 01 '11 15:03

phpheini


People also ask

Which is better echo or print in PHP?

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 .

Can you echo a HTML file in PHP?

Using echo or print: PHP echo or print can be used to display HTML markup, javascript, text or variables.

What does echo in PHP do?

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.

How do I echo an HTML file?

You should use readfile() : readfile("/path/to/file"); This will read the file and send it to the browser in one command.


2 Answers

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 :)

like image 35
Sarfraz Avatar answered Oct 13 '22 01:10

Sarfraz


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.

like image 171
Mario Avatar answered Oct 12 '22 23:10

Mario