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?
Related
What I keep seeing is something like
<?php $page_title = ""; ?>
<?php include_once("inc/header.php"); /* Include Header */ ?>
versus
<?php
$page_title = "";
include_once("inc/header.php"); /* Include Header */
?>
I assume there is no difference in functionality (not sure however), but which way is more semantic / correct does it matter if you declare all your PHP in several PHP blocks or a single one? Is performance affected in any way?
This is a major reason why doing your PHP inline is going out of style. There's no performance hit that I know of. All <?php ?> does is tell the interpreter that this is to be processed by PHP so your first code block is saying
Stop parsing PHP
Start Parsing PHP
I would imagine there's some miniscule hit somewhere if you're trying to wring every last ounce of efficiency out but I consider it to be insignificant. It's important to userstand that if you're using opcode cache (and you should) then the only hit is on the parsing side. Repeated execution of cache will have 0 effect here.
Readability, however, really does demand your code be as compact as possible. Remember, someone may come behind you and work on this code. Having two blocks where only one is needed is inefficient.
There is no real answer to this.
Some people like to have it the "Code-Block"-Way and put it all in one set of tags, some other people prefer the "HTML-Tag"-Way where they put each command in a new set of tags
There is no difference in functionality except for the fact that everything between one ?> and the next <?php gets echo'ed (So you have a lot of spaces in your output HTML, which is okay, since they are ignored)
Performance might be affected, but in numbers you really don't need to care about.
Generally, if you are in templates (or lets say, PHTML, HTML and PHP mixed), try to keep all commands single-lined (Put all single commands in <?php ?> and on own lines), this will make it more readable between all those HTML tags.
If you don't have HTML in your PHP file, there is no reason to enclose all commands with PHP tags
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.
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.
My friend writes everything using phps echo.
I mean he starts <? and echo everything, including header, main part, footer, he even has style.php file where he echos some css and then includes it in main project.
question is why is it better to do that way ? Or is it better at all?
Cause in dreamveawer everything is red. I mean it understands evrything as phps srtings and makes all text red.
If you do not use echo you have different colors in code and you can see where is ccs, javascript or html.
So what's better to write normally or I should try the same "echo everything" practice ?
No, it is no better to do that way.
Do not use echo to output HTML but divide your code into 2 parts - business logic part and presentation logic part, a latter one consists of mostly HTML with PHP used only to output data coming from the business logic part
a little example of such a template:
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
If that's how he does it, then please slap him across the back of the head for us please?
But seriously, there is this thing called MVC, please take a look at it, comprehend it, implement it and explain it to your friend.
That's horrendous.
You should try not to mix PHP and HTML if you can help it.
In some cases you will be interleaving some dynamic content with static content (and you could use a templating engine for that); but outputting the entire HTML document via PHP statements is a clear sign of insanity and sadism.
You might be interested in templates. They're not html nor php, but a combination between these two.
The advantage is that you can see/edit/update/maintain your code much easier, because the actual php part is somewhat separated from the html markup.
The main disadvantage is that it might be a bit slower, since php reads the template, makes replacements and then spits out the html.
Here's a link to some of the most used php template engines.
Using HTML code instead of echoing has the advantage that the editor (Dreamweaver in your case) can do syntax highlighting. This will help you find errors in your HTML faster.
Also, you don't have to think too much about escaping quotes in your HTML (you still need to think about proper escaping your PHP variables anyway).
I can think of several ways the bad habit of echoing everything can be formed:
Errors from missing PHP tags while intermingling PHP and HTML. For a newbie it takes a while to wrap your head around the concept of using one language (PHP) to write code in another language (HTML). I remember when I first learned PHP I thought it would be easier to echo everything instead of opening and closing PHP tags all the time.
Coming from a language background where every output must be printed explicitly.
Having read some insane micro-optimization article on the web that claims echoing is faster or more secure.
This question already has answers here:
How to properly indent PHP/HTML mixed code? [closed]
(6 answers)
Closed 9 years ago.
This has been bugging me today after checking the source out on a site. I use PHP output in my templates for dynamic content. The templates start out in html only, and are cleanly indented and formatted. The PHP content is then added in and indented to match the html formating.
<ul>
<li>nav1</li>
<li>nav2</li>
<li>nav3</li>
</ul>
Becomes:
<ul>
<?php foreach($navitems as $nav):?>
<li><?=$nav?></li>
<?php endforeach; ?>
</ul>
When output in html, the encapsulated PHP lines are dropped but the white space used to format them are left in and throws the view source formatting all out of whack. The site I mentioned is cleanly formatted on the view source output. Should I assume they are using some template engine? Also would there be any way to clean up the kind of templates I have? with out manually removing the whitespace and sacrificing readability on the dev side?
That's something that's bugging me, too. The best you can do is using tidy to postprocess the text. Add this line to the start of your page (and be prepared for output buffering havoc when you encounter your first PHP error with output buffering on):
ob_start('ob_tidyhandler');
You can't really get clean output from inlining PHP. I would strongly suggest using some kind of templating engine such as Smarty. Aside from the clean output, template engines have the advantage of maintaining some separation between your code and your design, increasing the maintainability and readability of complex websites.
i admit, i like clean, nicely indented html too. often it doesn't work out the way i want, because of the same reasons you're having. sometimes manual indentation and linebreaks are not preserverd, or it doesn't work because of subtemplates where you reset indentation.
and the machines really don't care. not about whitespace, not about comments, the only thing they might care about is minified stuff, so additional whitespace and comments are actually counter-productive. but it's so pretty *sigh*
sometimes, if firebugs not available, i just like it for debugging. because of that most of the time i have an option to activate html tidy manually for the current request. be careful: tidy automatically corrects certain errors (depending on the configuration options), so it may actually hide errors from you.
Does "pretty" HTML output matter? You'll be pasting the output HTML into an editor whenever you want to poke through it, and the editor will presumably have the option to format it correctly (or you need to switch editors!).
I find the suggestions to use an additional templating language (because that's exactly what PHP is) abhorrent. You'd slow down each and every page to correct the odd space or tab? If anything, I would go the other direction and lean towards running each page through a tool to remove the remaining whitespace.
The way I do it is:
<ul>
<?php foreach($navitems as $nav):?>
<li><?=$nav?></li>
<?php endforeach; ?>
</ul>
Basically all my conditionals and loop blocks are flush left within the views. If they are nested, I indent inside the PHP start tag, like so:
<ul>
<?php foreach($navitems as $nav):?>
<?php if($nav!== null) : ?>
<li><?=$nav?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
This way, I see the presentation logic clearly when I skim the code, and it makes for clean HTML output as well. The output inside the blocks are exactly where I put them.
A warning though, PHP eats newlines after the closing tag ?>. This becomes a problem when you do something like outputting inside a <pre> block.
<pre>
<?php foreach($vars as $var ) ?>
<?=$var?>
<?php endforeach; ?>
</pre>
This will output:
<pre>
0 1 2 3 4 5 </pre>
This is kind of a hack, but adding a space after the <?=$var?> makes it clean.
Sorry for the excessive code blocks, but this has been bugging me for a long time as well. Hope it helps, after about 7 months.
You few times I have tidied my output for debugging my generated HTML code I have used tabs and newlines... ie;
print "<table>\n";
print "\t<tr>\n";
print "\t\t<td>\n";
print "\t\t\tMy Content!\n";
print "\t\t</td>\n";
print "\t</tr>\n";
print "</table>\n";
I about fell over when I read "I'm really curious why you think it's important to have generated HTML that's "readable". Unfortunately, there were quite a few people on this page (and elsewhere) that think this way...that the browser reads it the same so why worry about the way the code looks.
First, keeping the "code" readable makes debugging (or working in it in general by you or a developer in the future) much easier in almost all cases.
Furthermore, AND MOST IMPORTANTLY, it's referred to as quality of workmanship. It's the difference between a Yugo and a Mercedes. Yes, they are both cars and they both will take you from point "A" to point "B". But, the difference is in the quality of the product with mostly what is not seen. There is nothing worse than jumping into a project and first having to clean up someone else's code just to be able to make sense of things, all because they figured that it still works the same and have no pride in what they do. Cleaner code will ALWAYS benefit you and anyone else that has to deal with it not to mention reflect a level of pride and expertise in what you do.
If it's REAL important in your specific case, you could do this...
<ul><?php foreach($navitems as $nav):?>
<li><?=$nav?></li><?php endforeach; ?>
</ul>
Although that is worse in my opinion, because your code is less readable, even though the HTML is as you desire.
I don't care how clean the output is - it's the original source code that produced it that has to be easy to parse - for me as a developer.
If I was examining the output, I'll run it through tidy to clean it up, if it were required to take a good look at it - but validators don't care about extra spaces or tabs either.
In fact, I'm more likely to strip whitespace out of the output HTML than put any in - less bytes on the wire = faster downloads. not by much, but sometimes it would help in a high traffic scenario (though of course, gzipping the output helps more).
Viewing unformatted source is very annoying with multiple nested divs and many records each containing these divs..
I came across this firefox addon called Phoenix Editor. You can view your source in it's editor and then click "format" and it works like a charm!
Link Here
Try xtemplate http://www.phpxtemplate.org/HomePage its not as well documented as id like, but ive used it to great effect
you would have something like this
<?php
$response = new xtemplate('template.htm');
foreach($navitems as $item)
{
$response->assign('stuff',$item);
$response->parse('main.thelist');
}
$response->parse('main');
$response.out('main');
?>
And the html file would contain
<! -- BEGIN: main -->
<html>
<head></head>
<body>
<ul>
<! -- BEGIN: thelist -->
<li>{stuff}</li>
<!-- END: thelist -->
</ul>
</body>
</html>
I Agree, A clean source is very important, Its well commented, well structured and maintence on those sources, scripts, or code is very quick and simple. You should look into fragmenting your main, using require (prior.php, header.php, title.php, content.php, post.php) in the corresponding places, then write a new function under prior.php that will parse and layout html tags using the explode method and a string splitter, have an integer for tab index, and whenever </ is in the functions string then integer-- whenever < and > but not /> and </ are in the string integer ++ and it all has to be placed properly.... , use a for loop to rebuild another string tabindex to tab the contents integer times.