Twice now that I have asked and was responded that I should separate PHP from HTML in codes as much as possible. Instead of using:
<?php
echo "<p>The value of x is $valuex greater.</p>";
?>
That I should use:
<p>The value of x is <?php echo $valuex; ?> greater.</p>
Is there any difference I should know other than the format?
One of the unique things about PHP is that it serves the purpose of both a server-side language and a templating language. Ideally, your code would be separated into controllers and views, where your controllers are pure PHP (without any HTML) and your views are mostly HTML (with minimal PHP). When you're writing a controller, PHP is just like any other server-side language. But when you're writing a view, PHP becomes a templating language, in which case HTML should rule.
Another good reason to separate the two is syntax highlighting. In your first example, most editors wouldn't realize that the text within the string is actually HTML, so they wouldn't know to apply syntax highlighting. This means your code will likely be harder to read than it could be, making life difficult for subsequent developers.
The difference is:
<?php $valuex = 6; ?>
<p>The value of x is <?php echo $valuex; ?> greater.</p>
Here you need to echo only php variable part.
<?php
echo "<p>The value of x is $valuex greater.</p>";
?>
Here you need to echo whole part.
You need echo in second one,
<p>The value of x is <?php echo $valuex; ?> greater.</p>
Or simply,
<p>The value of x is <?=$valuex ?> greater.</p>
Read: What's the best way to separate PHP Code and HTML?. Also read Escaping From HTML.
The output will be the same in both cases.
The first example is PHP outputting HTML code
The second example is HTML code with PHP inside it
The "Ideal" example is this:
<p>The value of x is <?=$valuex?> greater.</p>
On the first one change the syntax like
<?php
echo "<p>The value of x is ".$valuex." greater.</p>";
?>
and in the second one change to echo the value like
<p>The value of x is <?php echo $valuex; ?> greater.</p>
But both the notations are same,and work same
The reason for this is that frankly you'll want to always be as flexible as possible. However, mixing your php with html means that your php-core is mixed up with your template, thus you'll have an a lot harder time maintaining, altering & providing different templates/languages etc. Thus always keep it apart.
It's much easier to maintain your code, both HTML and PHP, when separating them.
Related
This question already has answers here:
Is there harm in outputting html vs. using echo?
(4 answers)
Closed 5 years ago.
Is there a difference between this
<?php
myCode();
echo "Example";
?>
and
<?php
myCode();
?>
Example
this?
What is the best choice in terms of performance?
I've done a Benchmark printing 20000000 times "Example". I've executed the script from CLI, not through HTTP request (Centos 7 64bit).
Using "echo": 153.06723901367sec
Using HTML: 155.80555395508sec
For all pragmatic purposes, no, there is no relevant difference. Your script output will be "Example" in both cases. And in both cases, myCode() was executed before.
In fact, the OPCodes in both cases will be the same, because PHP will echo everything outside of <?php tags. It's basically just an implicit echo.
Technically, the way to the resulting OPCodes will be different, but this has no relevant impact on performance. Mostly anything outside <?php tags is treated as T_INLINE_HTML by the parser. This is then converted to an echo in the abstract syntax tree:
| T_INLINE_HTML { $$ = zend_ast_create(ZEND_AST_ECHO, $1); }
with ZEND_AST_ECHO being
case ZEND_AST_ECHO:
APPEND_NODE_1("echo");
However, your aim should be to separate logic from your views and templates as good as possible as it can easily lead to spaghetti code if you don't. As a rule of thumb, a function should not echo, but return strings. Most frameworks only echo once: at the end of a request when rendering the response.
Since you mentioned "Views" and MVC: a View in MVC is not necessarily a template, but a specific representation of a particular piece of data from the Model. It can be code that ultimately renders a template though. If that's what you want, you probably want to check out a template engine, like Twig (although PHP is a template engine on it's own).
Yes. The 1st is PHP, the 2nd is HTML.
In the first case you could do:
<?php
$var = 1;
echo "Example " . $var;
?>
The second case $var is undefined in the HTML so would be ignored.
<?php
$var = 1;
?>
Example $var
If you wanted to use that variable in the HTML you would need to go back into PHP i.e.
<?php echo $var; ?>
This is a preference thing in my experience, there are some pages that are mostly HTML that can be written that way. However, if I am writing PHP I prefer to stick with PHP and not bounce between the 2 languages. I don't know of anything that you can do in HTML that you can't produce from PHP. It makes for nasty looking code that is hard to debug.
Also there are issues with HTML headers (see PHP header() Function).
I'm rather new to programming and i know how to separate PHP from HTML, but i would like to know if there is any difference in doing
this:
<?php $rand="I love apples" ?>
<h1>This is a title</h1>
<div>
<p>This is a paragraph</p>
<?php echo"The variable contains the string $rand"; ?>
</div>
?>
compared to doing this:
<?php
echo "<h1>This is a title</h1>";
echo "<div>";
echo "<p>This is a paragraph</p>";
echo "The variable contains the string $rand";
echo "</div>";
?>
Is there any difference between in performance etc, between splitting the PHP code from the HTML code and just echoing the whole page in php?
The best practice is not to seperate PHP from HTML, the best practice is to seperate logic from markup.
Also important is coding style. Proper line indentions. Using echo "</div>"; instead of echo"</div>";, valid HTML, not putting variables into quotations:
echo "The variable contains the string $rand";
better (why? see my comment below):
echo "The variable contains the string ",
$rand,
" :-)";
Your whole project gains much quality and worthness just by improving the code, writing clean, readable, maintainable. Imagine you want to change the Text, you would have to add or change lots of echoes.
Code Style Guides > Pear,
PSR, Zend <
encourage developers to keep their code readable, valid and cross-browser compatible
The problem is not performance, it's about readability and more importantly, maintainability.
Doing all the processing in one place, and all of the output in another (i.e. Logic and Presentation), would mean you will have an easier time altering one without affecting the other too drastically.
To your specific question, the top method is preferable by far, for the reasons listed above.
Taking your question at face value, there are two reasons that come to mind immediately:
Assuming you're using a smart editor, echoing all your HTML will cause you to lose syntax highlighting for it, so you're less likely to catch errors.
Because everything is inside a PHP string, now you have to worry about escaping all your other special characters. Try spitting out some Javascript with a string in it and let us know how fun that is.
However, when most people say something like "separating PHP from HTML" they are referring to the concept of separating your logic from your views. It means don't put complex business logic, computations, and database calls inside your html pages. Keep that all in pure PHP files, and have your html files contain minimal PHP that's only used to spit out your data.
<?php $rand="I love apples" ?>
<h1>This is a title</h1>
<div>
<p>This is a paragraph</p>
<?php echo"The variable contains the string $rand"; ?>
</div>
?>
The above looks poorly separated. This is what php/html separation should look like:
<?php
$rand="I love apples";
?>
<h1>This is a title</h1>
<div>
<p>This is a paragraph</p>
<p>The variable contains the string <?=$rand ?></p>
</div>
Performance-wise, that's not an issue but it would do much favor for programmers to be able to read the code easily, hence the need for HTML/PHP separation practices. Ideally, if you're going to do just one script, keep all your PHP code at top. Also, other reason for the separation is that IDE editors can easily format HTML nicely. If there's a HTML tag inside the PHP tag that is ending with a HTML tag outside of PHP, then HTML cannot be formatted correctly. For example:
<div><p>And it offers so much <?php echo "$features</p>
<h2>Proven Ideas";?></h2>
<p>More details ahead</p>
</div>
The above will run just fine but the IDE html formatter will likely be confused with missing end tags and won't format making it more difficult for programmers to read them.
I think you example is not a good one that makes it very clear why you should separate it.
The reason why you should separate not just HTML but the presentation, rendering or UI part of your application is clean coding and separation of concerns. This will make sure your get clean, easy to read code and makes your application maintable.
Take Wordpress for example, it is an extremely fugly mix of php and HTML. They even do SQL queries in the presentation layer of the application, if you can even draw a borderline between presentation and other logic in this thing.
You'll always have to output some dynamic content in your HTML but really try to reduce it to echoing variables and having some output formatting helper objects there. All business logic should be somewhere else, just not in the "templates" or whatever else you'll call the files that contain the output.
Have a look at the MVC pattern for example, it gives you a good idea of how and why you want to separate things.
In my opinion, it depends on the level of HTML formatting that is being done versus PHP logic. Nothing more & nothing less. It’s simply easier to read pure HTML as pure HTML or PHP as straight PHP. When it is all jummbled together—the way some templating systems handle it—it becomes a logical headache to read & debug. So I err on the side of placing HTML in PHP for my own sanity’s sake.
Unclear on the performance pluses or minuses if there are any. But can assure you that in 20+ years I have never had a server slow down because of too much HTML embedded in PHP
Personally, I would format your code example like this:
<?php
echo "<h1>This is a title</h1>"
. "<div>"
. "<p>This is a paragraph</p>"
. "The variable contains the string $rand"
. "</div>"
;
?>
I like this method since there is one echo—which makes it clear what is happening—and the rest of the HTML is just concatenated via . characters.
Also, remember all formatting in programming benefits HUMANS more than anything. A computer only needs to see the commands, so if you want to be pitch perfect for a machine, just code without any spaces or formatting. Heck, stop using full words & just use 1 letter variables! Oh wait, that is how it was done in ye olden days.
Nowadays compilers & caching systems are designed to take human readable code & make it machine optimized.
Which is all to say: You should code towards readability & logic on your part. Nothing more & nothing less.
Ok, someone has just shown me a piece of PHP code and at the end of the file I've seen a stray <?php } ?> . I thought that should give a compilation error, but it doesn't.
Why is:
<?php
if(1==1){
?>
X
<?php } ?>
valid?
Is it safe to split a statement into multiple php blocks?
PS: I was expecting for something more from the answers then "yes" :D
Yes that is fine, but I would suggest:
<?php if(1==1):?>
X
<?php endif; ?>
It makes it a little more readable then random { and }
From the manual:
Everything outside of a pair of opening and closing tags is ignored by
the PHP parser which allows PHP files to have mixed content. This
allows PHP to be embedded in HTML documents, for example to create
templates.
Welcome to the mysterious world of PHP.
Safe? Yes.
Readable? Not really.
Avoid mixing your PHP logic with your HTML where possible. There are few times when this is a good idea, as it makes reading through and understanding your code difficult.
Yes, this is fine.
It's often useful to drop out of "php mode" for large blocks of HTML - you'll see this technique used anywhere HTML and PHP are mixed.
It is valid, but not recommended if you want to have a code that is maintainable and readable in the long run.
You must bear in mind that every time you "exit" from PHP, you are entering HTML.
Is there any difference between the following 2?
1 separate php code from html
<html>
<body>
<?php // php code 1 ... ?>
<div> ... </div>
<?php // php code 2 ... ?>
<div> ... </div>
<?php // php code 3 ... ?>
</body>
</html>
2 everything inside php
<?php
echo "<html>";
ehco "<body>";
// php code 1 ...
echo "<div> ... </div>";
// php code 2 ...
echo "<div> ... </div>";
// php code 3 ...
echo "</body>";
echo "</html>";
?>
Which is faster?
It is not the way to increase the speed. If you are not satisfied with your app performance - take profiler and find the slowest part. After that - optimize that slowest part.
The way "I optimize the things that it is easy to optimize" is always the worst.
The first one is faster because interpreter will take care only about the code inside the tags.
The second one should not be use, double quotes are interpreted to see if there is a variable inside. You should always use simple quote when you don't want string to be interpreted.
The usual usage is what you listed in the first form, although in some cases, such as a helper function to generate <a href="..." ... >link word</a>, then you will generate HTML inside PHP code. Or if you have a function that generates a table, or an ul with many li printed out with data from inside an array or hash.
Whatever performance difference you'll find is moot and academic. Choose the first form. The second form isn't future-proof. A simple change in the layout of the HTML page will require a software engineer. The first will just require a creative designer.
With an opcode cache installed on the server (see: APC, eAccelerator), it doesn't matter either way, as the page only has to be interpreted the first time it's accessed.
Performance:
Perhaps the 2nd example would be slightly slower because it does more function calls & also when a string is inside double quotes then the interpreter will look for variables to substitute and escape sequences, eg. \n
PHP blocks also need to be parsed. This may be irrelevant is your script is pre-compiled / running on an accelerator.
Formatting:
1st example will produce HTML code automatically formatted with indentation.
The 2nd example will produce code that's all on one line. Not really an issue as this can be corrected.
Readability:
Perhaps the first example is more readable. Eg. IDE can highlight syntax for HTML and separately for PHP
Others:
2nd example would probably be more preferred choice if the code is in a framework and markup gets extracted in to smaller function(s), sub-classed, etc?
For the most part, when I want to display some HTML code to be actually rendered I would use a 'close PHP' tag, write the HTML, then open the PHP again. eg
<?php
// some php code
?>
<p>HTML that I want displayed</p>
<?php
// more php code
?>
But I have seen lots of people who would just use echo instead, so they would have done the above something like
<?php
// some php code
echo("<p>HTML that I want displayed</p>");
// more php code
?>
Is their any performance hit for dropping out and back in like that? I would assume not as the PHP engine would have to process the entire file either way.
What about when you use the echo function in the way that dose not look like a function, eg
echo "<p>HTML that I want displayed</p>"
I would hope that this is purely a matter of taste, but I would like to know if I was missing out on something. I personally find the first way preferable (dropping out of PHP then back in) as it helps draw a clear distinction between PHP and HTML and also lets you make use of code highlighting and hinting for your HTML, which is always handy.
The first type is preferable, exactly for the reasons you mentioned.
Actually, echoing out whole chunks of html is considered bad practice.
No, there's no performance increase that would be visible.
Sometimes its just simply easier to output content using echo (for example, when inside a while or for loop) than to close the php tag.
I think there's a preprocessor which converts the same form into the second. That's what happens in ASP.NET, anyway. And in both ASP.NET and classic ASP, loops can actually stretch across raw-HTML regions.
There's no performance difference at all.
Just the style that produces the most readable code. Depending on the actual situation that can be either of the two.
But mixing HTML and PHP should be avoided where possible anyway. THis can be accomplished by using a template system for your views.