Related
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.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the correct way to format the code? and why is it so necessary? Why should all programmer follow the same rule of formatting and basically, what is the rule??
Why programmer prefers to write as
<html>
<head>
<title>Title</title>
</head>
<body>
<!--body-->
</body>
</html>
instead of
<html>
<head>
<title>Title</title>
</head>
<body>
<!--body-->
</body>
</html>
Could someone please make it more clear? and, is there any special thing about javascript and css formatting? What are the advantages and disadvantages of formatting?
There are no correct way in formatting.
Newlines and indentations are usually done only for human readability (except some language like Python) and no one true standard that everyone agrees upon.
It's about being able to look back at your code and easily being able to see what sections are blocks of code that are contained within other tags. Frequently you'll have lots of divs in a page, with many divs contained within other divs. Simple indenting can help work out which matches the opening div you're currently looking at.
<div id='start'>
<div id='insideStart'>
<div id='insideInsideStart'>
</div>
</div>
</div>
would not look as clear as
<div id='start'>
<div id='insideStart'>
<div id='insideInsideStart'>
</div>
</div>
</div>
This is a question well suited to be read in such books as
Clean Code
Pragmatic Programmer
But to answer your questions.
First off: "Why programmer prefers to write as..."
This is solely to make the code more clear and further it more adheres to structure.
Structure to make what you're making clearer to me as a human and fellow coder.
Adhering to a set standard of naming conventions and structure helps new developers get in to your code faster and it will be less prone to bugs such as typos and common mistakes.
The other question you're asking is: "What are the advantages and disadvantages of formatting"
Advantages - all of the above
Disadvantage - It might be a performance hit but I think not.
And the last question you ask is "Why should all programmer follow the same rule of formatting and basically, what is the rule??"
There is no clear rule on how you should code as long as you follow your teams convention.
This makes it easier for developers after you that has the dirty job of cleaning up your mess or trying to figure out your way of thinking when you did that one function which is now starting to get old or is bugging out.
There are however some "common ways", if you will, when naming variables and functions and so on and these are explained in detail here.
These are for javascript, which you are asking for, but most of it can be used in other languages as well.
I hope this answers your questions.
But as #BoltClock said, and this is what you should aim for, make your code clear. This is number one priority of all programmers, or well, it should be.
The big thing for me (with HTML in this example, but it carries over to programming as well) is to tell scope.
Your HTML example is pretty simplistic, but often times there are far more nested structures which can get quite confusing. For example:
<html>
<head></head>
<body>
<div id="container">
<div class="shadow">
<div class="inner">
<h1>Hello World</h1>
</div>
<div id="handle">
<span id="foo">Bar</span>
</div>
</div>
<div id="morefoo">
<h3>Hi</h3>
</div>
</div>
</body>
</html>
If I told you to add another div to the div with class shadow, you may need to do some <div> </div> counting. But with the markup formatted below, it is pretty easy.
<html>
<head></head>
<body>
<div id="container">
<div class="shadow">
<div class="inner">
<h1>Hello World</h1>
</div>
<div id="handle">
<span id="foo">Bar</span>
</div>
</div>
<div id="morefoo">
<h3>Hi</h3>
</div>
</div>
</body>
</html>
As of writing down HTML markup or CSS - this is not about programming.
Anyway the standard of writing a clear and clean HTML markup is to indent any child element by one tab thus the code looks like in Your first example. This way the code get nicely structured and readable.
As of writing down the CSS code there is no standart AFAIK, but I saw three styles of formatting the CSS code:
1.
body { ... }
div#container { ... }
div#container #left-column { ... }
2.
body {
...
}
div#container {
...
}
div#container #left-column {
...
}
3.
body {
...
}
div#container {
...
}
div#container #left-column {
...
}
The difference between the second and the third example is in that in the third example by indenting div#container #left-column by one more tab You are showing off that this rule is for the element that is inside the parent div#container. The first example keeps the CSS code more compact but is less readable and is not very good option when having many rules on that one line (the line could get very long).
As of writting down the JS code here the rules for formatting should same (or at least very similar) as when writting down the PHP code...
In most cases, formatting is there for the benefit of the programmer, not for the computer.
As far as the computer is concerned, the indentation is completely irrelevant. This can be seen in action with "code minimizers", which take a program and remove all the white space to compress it and make it into a smaller download. Likewise there are "code tidier" tools, which do the opposite -- take a badly formatted program and set the indentation so that it is more readable.
So the real reason for indenting code is to make it readable. It's for your benefit.
You may think your code is perfectly readable without indentation, but I can assure you it isn't. If you think it is, try coming back to some of your old code after six months of not reading it. But it's not just for your own sake; if you need to share the code with others -- say on a site like this one -- other people will find your code much easier to read, and therefore much easier to help you, if they can read your code easily.
* Note: The exception to all this are a handful of languages like Python in which the indentation is a significant part of the code, and tells the program which lines are part of which structure. In these languages, indentation is a part of the language, so it's there for the program as well as for the programmer.
You should understand that for compiler there is totally no difference in performance for code like this:
<html>
<head>
<title>Title</title>
</head>
<body>
<!--body-->
</body>
</html>
and this
<html>
<head>
<title>Title</title>
</head>
<body>
<!--body-->
</body>
</html>
and even this
<html> <head><title>Title</ title></head>
<body><!--body--></body> </html>
All of them would compile and work the same way with totally same performance.
However, main purpose for code formatting is readability. Dividing code in blocks like this makes it easier for programmer to understand, thus letting him see programm's logic more clearly.
It's easier to maintain and understand for you and people working with code after you.
All of this is resulting in more effecient development (since you waste less time on understanding code, since everything is organized, resulting in less development mistakes, less bugs, thus letting you spend more time on development, making development easier and faster).
The general rule of thumb is to indent code with 4 spaces or a tab. Many Open Source projects adhere to the 4 spaces rule in their coding standards, to name a few:
Apache
Android
WebKit
Zend
In your HTML example, it is less beneficial because the closing tags explicitly state their element type, it's still useful though for finding the opening/closing tags of nested divs and other elements.
In other languages that use the braces syntax (and one's that don't for example PLSQL), it is extremely helpful to indent code. Example:
for(...)
{
if(..)
{
while(..)
{
}
}
else
{
}
}
The above is hard to read compared to:
for(...)
{
if(..)
{
while(..)
{
}
}
else
{
}
}
With the indentation above, the flow of execution and the start/end braces of each block can easily and quickly be read.
As far as I know, these three rules govern the idea of code indentation.
Make it clear for your to read
To know the beginning and ending of a block of code
To leave it nicer, for someone who will work on your code latter
How to indent codes?
- I would base that, from a start to end of brackets or functions, or based on tasking as loops, arrays...
One big issue in coding is code maintenance. One developer always thinks that his code will work forever, is bullet proof and will never require any alteration. That is obviously not true. Hence, another dev will certainly have to dig in this code, which is usually difficult if the original coder has not formatted and documented his code.
Formatting is about readability and re-usability.
You can follow usually accepted guidelines, such as summarized there for javascript :
http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Code_formatting#Code_formatting
Every language has different coding standards, more or less popular.
Why use a coding standard : easier for you/your team/others to read, give the sense of "unity" in a project. Think that without coding standards in bigger projects you'll see code like this :
if (condition) return FALSE;
else {
$x=1;
} else $x=3;if (condition2) return true;
Examples for PHP coding standards :
Zend standard http://framework.zend.com/manual/1.12/en/coding-standard.coding-style.html
PEAR standard http://pear.php.net/manual/en/standards.php
Kohana standard http://kohanaframework.org/3.0/guide/kohana/conventions
A great way to make sure your site works properly is to write your HTML. This will allow you to focus on the content and the functions and test them before you start making everything pretty.
For more info read these two articles :-
1. The Significance of Proper Markup in Web Design
2. What Beautiful HTML Code Looks Like
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
text-overflow:ellipsis in Firefox 4?
I have the same issue mentioned in Truncating long strings with CSS: feasible yet?. It's been nearly two years since that post, and Firefox still ignores the text-overflow: ellipsis; property.
My current solution is to truncate long strings in PHP like so:
if(strlen($some_string) > 30)
$some_string = substr($some_string,0,30)."...";
That more or less works, but it doesn't look as nice or as accurate as text-overflow: ellipsis; in browsers that support it. The actual width of thirty characters varies since I'm not using a monospace font. The XML fix and jQuery plugins posted in the other thread appear to no longer work in Firefox either.
Is there currently a way to do this in CSS that is browser independent? If not, is there a way to measure the width of a string given a font and font size in PHP so that I might more accurately place my ellipsis?
This answer might be useful for getting your output truncated to the nearest word, and then simply append a … (…) HTML entity onto the end of the output to get your final output.
As you've noticed there's not sufficiently wide browser support yet the CSS solution yet, and you've still got to worry about old browsers too.
It is a shame that all browsers don't handle the same CSS features. However, you could always do something like this using JavaScript (with help from jQuery).
Here's an example of how such a thing might look: http://jsfiddle.net/VFucm/
The basic idea is to turn your string into an array of words, like so:
var words = full.split(/\s+/g);
Loop through them and take the first N (in this case I chose 24) and push them into another array:
for (var i = 0; i < 24; i++) {
short.push(words[i]);
}
Throw them back into the HTML element they came from:
$('.snip').html(short.join(" ") + ' <span class="expand">...</span>');
... here I added a "link" to expand the shortend text. It's made to look and act like a link using CSS. I also provided a function to replace the shortened text with the foll text again:
$('.expand').click(function() {
$('.snip').html(full);
});
I want a phone number which display on public page will be protected. Example converts phone number characters to HTML entities and bots can't grab the number in plain text. Let me know the trick.
This is a...passing thought, though I'm not sure how practical it would be:
<span class="protectedNumber" title="01234567890"></span>
css:
span.protectedNumber:before {
content: "Phone number: " attr(title);
}
JS Fiddle demo.
Edited, in response to 'cross browser?' question in comments, to add a jQuery option to assist with those browsers that don't have the ability to deal with css-generated content:
$(document).ready(
function(){
$('.protectedNumber').each(
function(){
$(this).text('Phone number: ' + $(this).attr('title'));
});
});
some ideas
display the phone number as an image
use javascript to create and display the phone number
throw in html tags in between the numbers (e.g. [span]) that visually makes no difference but makes it more difficult for the bot to recognize the phone number
Try writing the number using ASCII:
http://www.ascii.cl/htmlcodes.htm
<html>
<body>112</body>
</html>
The first thing I'd think of is render an image.
Use Javascript to obfuscate
Obfuscate using a php function
Sure just print the phone number using words instead of numbers...
Create an image of the number, this will foil MOST bots, but some may have OCR, so obfuscate it.
ie: Good:
Better:
The 2nd 1 better because like Captcha, the background contains "noise" that makes it hard for OCR enabled bots to harvest, but is as readable to human eyes..
The hard solution would be use Captcha or a simple PHP script to create the picture on the fly, but in most cases, unless you using alot of different #'s the "better" solution above easiest and quickest method, can do easy even in simple program like Paint in 5 min.
For the visually impaired, include a small link to an audio file (mp3) of you saying the number, if it linked properly, and accordingly, it should work.
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.