In terms of performance , what would be better. Using PHP to echo all the HTML output so I can pepper it with the various bits of working code and variables or escape HTML to php periodically throughout the documents.
I know there may be some readability issues but I'm not to worried about that.
Thanks all!
Example 1
echo '<html>',
'<body>',
'The content of the ',$container,' element is displayed in your ', $other_container,
'</body>',
'</html>';
OR
<html>
<body>
The content of the <?php echo $container; ?> element is displayed in your <?php echo $other_container; ?>
</body>
</html>
It's all about which you find the most readable. Of course, this will vary with each situation. If you were doing an entire page, and there were large sections which did not have any PHP in it, then I'd break out of PHP and just write the plain HTML, whereas if there was a section which had a lot of PHP variables, I'd do it all in PHP.
For example:
<table>
<tr>
<td colspan="<?php echo $numCols; ?>">
<?php echo $a; ?>, <?php echo $b; ?>, and <?php echo $c?>
</td>
</tr>
</table>
versus:
<?php
echo "<table>"
. "<tr>"
. "<td colspan=\"" . $numCols . "\">"
. $a . ", " . $b . " and " . $c
. "</td>"
. "</tr>"
. "</table>"
; ?>
Or
<?php
echo "<table>
<tr>
<td colspan='{$numCols}'>
{$a}, {$b}, and {$c}
</td>
</tr>
</table>";
?>
Also don't forget about printf
<?php
printf("<table>"
. "<tr>"
. "<td colspan=\"%d\">%s, %s and %s</td>"
. "</tr>"
. "</table>"
, $numCols
, $a
, $b
, $c
);
?>
Whichever is easiest to read.
The performance difference is pretty negligible compared to almost any other issue you'll encounter. Definitely readability is hands down the first issue here.
Let's cite the manual:
The example given here is contrived,
of course, but for outputting large
blocks of text, dropping out of PHP
parsing mode is generally more
efficient than sending all of the text
through echo() or print().
But please listen to the others and avoid this sort of micro optimization and choose the one that is more legible.
Can I propose a third solution? Have you heard of template engines? They help you create a clear separation between code and presentation which usually leads to cleaner code which is easier to maintain. A popular such template engine is e.g. smarty, but there are hundreds with different strengths.
It's pretty irrelevant to the overall speed of your app which one you go with.
That being said, I know you said you don't care, but please use the 2nd one as it's about a million times easier to read. And readability is huge.
I don't know about the performance of this, but within PHP you can also use what I believe is called a "Heredoc", which I think helps with readability within this sort of output.
Nickf's example:
<table>
<tr>
<td colspan="<?php echo $numCols; ?>">
<?php echo $a; ?>, <?php echo $b; ?>, and <?php echo $c?>
</td>
</tr>
</table>
becomes:
<?php
echo <<<EOT
<table>
<tr>
<td colspan="$numCols">
$a , $b, and $c
</td>
</tr>
</table>
EOT;
?>
I do believe that ultimately readability is a subjective thing, so your mileage may vary!
Ruth
It falls into the realm of micro optimizations. The largest part of your time falls into initializing the PHP engine starting the work.
So unless you have an order of tens of thousands of lines (or even more), you shouldn't be concerned with it.
To add, i did a small test of a million lines where i used php to print them and where i used php to call a c program that did the same thing and the difference was minuscule.
A little more info.
What is happening in the 2nd example is that you are "turning on/off" PHP, its not exactly what is happening but for this example it fits.
The thing you should be more worried about, is that code going to have a lot of logic around it? Am i going to split that string into even more strings or even place it in different places? Is this the View of a MVC application?
For 1 and 2 it could be a toss up between either method. But for 3 i would go with method 2 for these reasons.
A view in a MVC web application is mostly html/css. So i want to see that be formatted correctly and i want to see in my editor the html coloring. So that is a plus.
In terms of performance... it's not important. Readability of the code is king, a tiny fraction of a percent of performance difference isn't going to change anything.
The raw HTML version is usually the easiest to read (and probably has the best performance too for what it's worth - but what it's worth is: nothing). This is no surprise: PHP is an HTML templating language, the whole point is interleaving HTML at a language syntax level.
Look at nickf's code to see how to keep it readable. Indenting is important! Put a level of indenting inside each PHP control structure too, so you can keep track of them. eg.:
<?php if ($error) { ?>
<p> Oh no, error! </p>
<?php } ?>
Finally, when outputting content, such as $container in your example, you must always htmlspecialchars() it, or you'll have an application full of HTML-injection security holes, like every other PHP newbie (and even many professional developers, sadly). This matters whichever method you use to output content.
Because htmlspecialchars is quite an annoyingly long function name, you could try defining your own shortcut function:
<?php
function h($s) {
echo(htmlspecialchars($s, ENT_QUOTES));
}
?>
<ul>
<?php foreach ($things as $thing) { ?>
<li> <?php h($thing['name']) ?> </li>
<?php } ?>
</ul>
Code as if the next programmer taking over the project is a serial killer. In other words, use the second option you mentionned.
This should be considered more of a readability and maintenance issue than a performance issue.
Thus, option 2 has a couple concrete advantages:
Code coloring. With option 1 everything is colored as an echo statement which makes reading HTML more difficult.
Intellisense - With many IDE's, HTML within a PHP echo statement won't engage intellisense, so you'll be typing all that HTML by hand.
For small bits I just keep it all in PHP strings, like when looping through an array to generate a list. But for larger piles of markup I keep that out of the PHP and just drop into PHP when necessary.
This is largely because I prefer to optimize for maintainability. Not just because it's faster to see what's going on when the html has appropriate syntax highlighting applied, but because it also makes mistakes resulting from a flawed reading of the code less likely to occur.
There really isn't a best way. I just try to stay consistent with what's described above, and keep my eyes open for situations where maybe the other way would be a better way of handling it.
I prefer to use php heredoc function, this way I don't need to escape any characters, ex:
<?php
$title = "heredoc is cool!!!";
$mySite = "http://www.php.net";
echo <<<LOL
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> $title </title>
<link rel="shortcut icon" href="$mySite/favicon.ico">
<link rel="search" type="application/opensearchdescription+xml" href="$mySite/phpnetimprovedsearch.src" title="Add PHP.net search">
<link rel="alternate" type="application/atom+xml" href="$mySite/releases/feed.php" title="PHP Release feed">
<link rel="alternate" type="application/atom+xml" href="$mySite/feed.atom" title="PHP: Hypertext Preprocessor">
<link rel="canonical" href="$mySite/manual/en/language.types.string.php">
<link rel="shorturl" href="$mySite/types.string">
<link rel="contents" href="$mySite/manual/en/index.php">
<link rel="index" href="$mySite/manual/en/language.types.php">
<link rel="prev" href="$mySite/manual/en/language.types.float.php">
<link rel="next" href="$mySite/manual/en/language.types.array.php">
LOL;
?>
Note:
Heredoc text behaves just like a double-quoted string, without the
double quotes. This means that quotes in a heredoc do not need to be
escaped, but the escape codes listed above can still be used.
Variables are expanded, but the same care must be taken when
expressing complex variables inside a heredoc as with strings.
The latter is much more readable. It's also more easily editable (you do not have to escape quotes in HTML, for example). And it preserves whitespace without any hassle, which may be preferred, particularly for debugging purposes.
I almost wish PHP would enable print() and echo() to automatically convert HTML characters so that people would stop using them to generate HTML.
You should seriously consider never placing PHP inside of HTML. You are mixing logic with view which makes a project messy.
As others have said, if you output into html, use <?php echo $whatever; ?>
If you have to output a ton of information look into output buffering.
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.
Just to clarify: The issues "echo vs print" and "double quotes vs single quotes" are perfectly understood, this is about another thing:
Are there any reasons why one would prefer:
echo '<table>';
foreach($lotsofrows as $row)
{
echo '<tr><td>',$row['id'],'</td></tr>';
}
echo '<table>';
over:
<table><?php
foreach($lotsofrows as $row)
{ ?>
<tr>
<td><?php echo $row['id']; ?></td>
</tr><?php
} ?>
</table>
would either one execute/parse faster? is more elegant? (etc.)
I tend to use the second option, but I'm worried I might be overlooking something obvious/essential.
Benefits of first one
Easier to read
???
Benefits of second one
WYSIWYG is possible
HTML Code Completion/Tag-Matching possible with some IDEs
No escaping headaches
Easier for larger chunks of HTML
If I have a lot of HTML in a given PHP routine (like an MVC view) then I definitely use the 2nd method. But I format it differently - I strictly rely on the tag-like nature of PHP's demarcations, i.e., I make the PHP sections look as much like HTML tags as I can
<table>
<?php foreach($lotsofrows as $row) { ?>
<tr>
<td><?php echo $row['id']; ?></td>
</tr>
<?php } ?>
</table>
I agree with Peter Bailey. However, in views I use the alternative syntax for statements, and much prefer short tags (particularly for echoing). So the above example would instead read:
<table>
<? foreach($lotsofrows as $row): ?>
<tr>
<td><?= $row['id']; ?></td>
</tr>
<? endforeach; ?>
</table>
I believe this is the preferred standard for Zend Framework.
The first is far more readable in my opinion, however, the second technically involves less parsing. Any speed advantage in that case would likely be minor and really meaningless without profiling.
Premature Optimization is the root of all evil. Do what makes the code easiest to read and maintain. Efficiency takes a backseat to maintainability.
see http://en.wikipedia.org/wiki/Optimization_%28computer_science%29#When_to_optimize for some good advice on the subject
It's very dependable what you write.
PHP can be used as programming language, or as simple and powerful web-template language. Mixing of this two usages very, very bad practice and will be horrible to support in long term.
So Second style is more usable in templates with lot of html markup and little spots of code, first - for 'clear' php programming.
The best one is a template engine.
But, I think echo is way more cleaner and more readable (at least in this case - as pointed out in comments, it depends), than opening and closing tags everywhere (I don't know too much about PHP internals to tell which one is faster, though).
First one is more readable from programming point of view, but the second one allows you to open the file in some WYSIWYG HTML editor and change the page design.
I prefer the second option because it is much easier to tell your designer that "this part of the page will behave like that", than "this piece of code does that"
I've never seen something like this before. So, it's confusing me for a while. But now I understand and use it sometimes. So, after brief experience, can anybody tell me what is the pro and cons using Heredoc Notation in your PHP?
$stringval = <<<MYHEREDOC
just creating variable here. nothing more.
MYHEREDOC;
Personally, how do you use this PHP feature? Is it a bad way of coding or good way?
99% of the time I use it, it's for SQL queries eg:
$sql = <<<END
SELECT *
FROM sometable
WHERE value > 100
ORDER BY name
END;
I find it easier to spot such queries in the source code and copy and paste them into something to run them. Your mileage may vary. Note: you can do multi-line with normal strings. I tend to avoid this however as the first line is indented differently to the rest.
The biggest "pro" as far as I'm concerned is that you don't need to escape quotes. That's particularly an issue with markup. Decide for yourself which is easier to read. Assuming:
$name = 'foo';
$type = 'text';
$value = 'Default value';
Version 1: single quotes
$html = '<input type="' . $type . ' name="' . $name . '" value="' . $value . '">';
Version 2: double quotes
$html = "<input type=\"$type\" name=\"$name\" value=\"$value\">";
Version 3: heredoc
$html = <<<END
<input type="$type" name="$name" value="$value">
END;
Note: in version 2 you can of course use single quotes for attribute values to solve the escaping problem but the point is you have to worry about things like this. Personally I don't like to mix attribute quote types in markup either.
There are now two types of "Heredoc:"
Heredoc, similar to quotation marks "" will convert any variables into their value on creation. This is very useful for putting exact spacing/returns where you need them (no need for \n or \t).
Nowdoc, similar to single marks '' will NOT convert any variables and stores just the text value. This can be used in default values of class variables (unlike heredoc).
Heredoc Example:
$value = 5;
$string = <<<EOL
The number is $value
EOL;
// The number is 5
Nowdoc Example:
$value = 5;
$string = <<<'EOL'
The number is $value
EOL;
// The number is $value
EDIT: The only downside I can think of is that the ending characters (in the examples, EOL) MUST be preceded by 0 spaces. This is hard to remember and looks ugly when inside nested functions:
function foo() {
if ($bar) {
$string = <<<LINE
Hey, how is it going, $name.
This is a great test of Heredoc and Nowdoc.
Blah blah blah, go upvote me!
LINE;
}
}
Well, the pro(s) is
it's handy for large chunks of text with quotes
and the cons
you rarely if ever need large chunks of text in MVC
breaks indentation
has some quirks if used with classes (prior to 5.3)
Personally, i don't use it.
(an obligatory disclaimer about all this being a matter of preference, etc etc)
I don't use it at all. It was quite useful in Perl, as Perl had no HTML escape feature. So, PHP does, and if I want to print out large amount of text, i'd just close PHP tag and type text as is. In any other case old good double quotes suits me well.
HEREDOCs are very useful for dumping large blobs of text into a variable, or directly out to the client. It also saves you multiple concatenations if you're building up a long multi-line string. The only main drawback is you need to pre-process any data you'll be inserting.
echo <<<EOF
<input type="text" name="foo" value="$bar" />
EOF;
is very readable, especially with an syntax-highlighting editor. But you do need to pre-process $bar with htmlspecialchars() OUTSIDE there heredoc (for escaping quotes), so you end up with:
$bar = htmlspecialchars($bar);
echo <<<EOF
etc....
Whereas if you're in "html mode", you could use:
<input type="text name="foo" value="<?php echo htmlspecialchars($bar) ?>" />
or
echo '<input type ... snip ... value="' . htmlspecialchars($bar) . etc....
Generally you don't need to store the escaped version of the data, so you might as well dump it out directly and save yourself the variable assignment step. HEREDOCs don't let you do that, as you can't insert a function call into them directly.
It is very useful to have a very neat programming style segregating html with php. Your php codes will be very readable and easier to understand. It facilitates debbuging codes considerably. It allows you to concentrate more on the logic of the program rather than the presentation with html. You just need one echo statement rather than the annoying php scripts all over within your html. To illustrate how it is being use, here is an example.
masterpage.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title><?php $title ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="../js/jquery.min.js" type="text/javascript"></script>
<link href="../bsa.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript" src="../js/sortEligibility.js"></script>
<body>
<div id="maincontainer">
<div id="menu">
<ul id="navtop">
<li><*linkhere* title="Home">Home</a></li>
<li >*linkhere* title="Eligibility">Eligibility</a></li>
<li >*linkhere* title="Registration List">Registration</a></li>
<li ><*linkhere*" title="BSA Ranks and Requirements ">BSA Ranks</a></li>
<li><*linkhere* title="Merit Badges">Merit Badges</a></li>
</ul>
</div>
<div id='contentcolumn'>
<?php echo "<h2>".$title."</h2>".$bodyhtml;?>
</div>
<div id="footer">Footer</div>
</div>
</body>
</html>
meritBadges.php
<?php
//include dbase connection
include("*linkhere*/includes/dbconnect.php");
//this page is called where the value id_scout is sent through GET
//Show required output
$result = mysql_query("SELECT e.id_merit, m . *
FROM bsa_merits AS m
LEFT JOIN bsa_earned_merits AS e ON e.id_merit = e.id_merit
WHERE id_scout = '{$_GET[id_scout]}'");
while($row = mysql_fetch_assoc($result)){
$body .=<<<__HTML_END
<td align="center"><img_src="*linkhere*/MeritBadges_Files/{$row['filename']}"><br>{$row['merit']}</td>
__HTML_END;
}
if(!empty($body)){
$bodyhtml =<<<__HTML_END
Earned Merits:
<table border="0" cellpadding="5" cellspacing="0">
<tr>
$body
</tr>
</table>
__HTML_END;
}
else{
die ("There is nothing to display");
}
mysql_free_result($result);
$title="Merit Badges" ;
include("masterpage.php");
?>
All other pages may be created in similar fashion with the above example. Remember you just create one big string for your output and display it in your hmtl file with just one echo!
Just analyze the above codes and see how you can improve your php programming with heredoc!
Is it a bad way of coding or good way?
You mean, Is it good practice or is it bad practice?
Generally, there's nothing wrong with using it. I'd go as far to say there's something wrong with not using it:
You don't have to escape single and double quotes
Allows you to append to a previous variable while defining a "context"
Allows straight-up non-PHP markup (Such as Javascript) to be used alongside PHP; makes non-PHP code noticeable
No noticeable differences in performance[*]. Even so, it's trivial.
Of course there's nothing wrong with $var = "Welcome, <b>$user</b>;" - However, it's not ideal if you intend to work with large quantities of foreign code and wish to maintain readability:
Really, it's an ideal way to deal with markup such as HTML if you can't output it directly.
[*]Based off personal tests, but should remain true regardless.
Whilst it is acceptable to use HEREDOC, the major downside in my opinion is that most IDE's lose the ability to track the code, and often display messages where closing tags cannot be found - particularly if an opening tag inside a different HERDOC to the the end tag, or the code is a mixture of all styles. One of the applications I inherited was all over the place. For example.
echo <<<PART1
<table>
<tr>
....
</tr>
PART1;
//more php code
?>
</table>
This is a bad example, where some code is in a HEREDOC, such as the start of the table, and then much later down the code, the table is closed normally outside of PHP tags. My IDE (phpstorm 2017) complains that it cannot find matching table tags.
For this reason, I always convert the HEREDOCs I find into single quote versions. I also dislike escaping, so the single quote method looks tidiest for me.
But that's just my opinion....
When working with open source project (like wordpress, drupal, joomla) I always find in the PHP pages a syntax like (this is an example from drupal):
<?php if ($linked_site_logo or $linked_site_name): ?>
<?php if ($title): ?>
<div class="logo-site-name"><strong>
<?php if ($linked_site_logo): ?><span id="logo"><?php print $linked_site_logo; ?></span><?php endif; ?>
<?php if ($linked_site_name): ?><span id="site-name"><?php print $linked_site_name; ?></span><?php endif; ?>
</strong></div>
<?php else: /* Use h1 when the content title is empty */ ?>
<h1 class="logo-site-name">
<?php if ($linked_site_logo): ?><span id="logo"><?php print $linked_site_logo; ?></span><?php endif; ?>
<?php if ($linked_site_name): ?><span id="site-name"><?php print $linked_site_name; ?></span><?php endif; ?>
</h1>
<?php endif; ?>
<?php endif; ?>
while I do use a different syntax writing my scripts; if I did wrote the previous example it would look something like:
<?php
if($linked_site_logo or $linked_site_name){
if($title){
echo '<div class="logo-site-name"><strong>';
if($linked_site_logo){ echo '<span id="logo">' . $linked_site_logo . '</span>'; }
if($linked_site_name){ echo '<span id="site-name">' . $linked_site_name . '</span>'; }
echo '</strong></div>';
}else{ /* Use h1 when the content title is empty */
echo '<h1 class="logo-site-name">';
if($linked_site_logo){ echo '<span id="logo">' . $linked_site_logo . '</span>'; }
if($linked_site_name){ echo '<span id="site-name">' . $linked_site_name . '</span>'; }
echo '</h1>';
}
}
?>
Now, lets skip the 'appareance' of the 2 syntax methods, becose it is maybe a matter of taste and/or custom (obviously I prefer the second method), the question is:
Does the first syntax (breakinf the 'if' statements, output the HTML instead of echo it, have a lot of PHP snippets even if they arent really needed) have some technical advantages over the second one? (for example the script run faster, is easier to debug, etc...)
Or is just a open source programmers unwrited convention?
It's all about readability.
I don't know what you mean by output vs echo. There is no difference. They're just different ways of printing "stuff" to output that is sent to the client.
The disadvantage of:
echo "<div id=\"blah\">";
is twofold:
The extra slashes require effort to put in and make it less readable; and
HTML outside PHP code blocks will syntax highlighted by most PHP editors.
I wouldn't go as far as saying echoing HTML is evil in all cases, but it certainly has a lot of drawbacks. In addition to what cletus points out, your HTML is not structured anymore, i.e. the indention levels give you no indication of where you are in the document structure. That's a biggie for me.
Personally, I dislike the first style as well, as it makes the PHP code harder to read. I always try to strike a balance, multi-line PHP statements belong in one <?php ?> block, but HTML always belongs outside the <?php ?> block. In edge cases, e.g. when indention levels change inside the PHP block, I tend towards closing it and beginning a new block.
I can see that that opens up a can of worms regarding edge cases and when to use which, so I'm sympathetic to open source projects setting a formal rule to always close <?php ?> blocks.
The biggest "advantage" I could see to the former method would be that it's easier to insert HTML anywhere within the overall control flow - if you wanted to output some HTML before the if($title) check, you could just insert a line above it with the HTML, no need to escape things for an echo or whatnot.
afaik The reason for this is that graphic designers can edit the HTML in their tools (dreamweaver and similar). Those tools would show the php tags as just that or even hide them completely. That way they can design away without touching your code, which is, believe me, a massive advantage when collaborating with designers.
Actually they are not the same. in fact in your second example, php interpreter will do unnecessary step, which is printing out html elements. thus resulting poor performance depending on the size of the page. checout google's article "lets make web faster" http://code.google.com/speed/articles/optimizing-php.html.
They are the same. I suggest you stick what you have been used to do because that is more readable to you.
If you follow MVC - you have the view and model (domain logic) parts. For the view you use the first method because it's HTML with tiny PHP parts in it, and for the model you use the second method - it's pure PHP anyway. It's a very common approach afaik.
Examples:
Zend Framework - see zend view manual
WordPress - the code (even messy parts) are method 2, and the themes are method 1
Keeping one hierarchy of consistent indentation for both code and markup is essential for coping with complex templates. In the first example I can immediately see the structure of the tags; the second makes me work to understand what's going on. Without reading through it I can't see whether it's doing something like leaving an element open. IMO PHP should be written like XHTML, as if the ‘if’ statements were tags you had to balance.
(Personally though I prefer the standard {...} syntax to the alternative :...endif one. I don't see what advantage that brings.)
Legend has it that direct PHP-templated output is marginally faster than echoing everything. But if there's really any difference it's too small for me to measure. Certainly compared to any other work your script will be doing, it's inconsequential. t's only the readability that really matters. PHP is a templating language, though — you might as well take advantage of it!
[both examples fail to htmlspecialchars, tsk.]
In PHP, whenever I do something like:
<span>Blah blah HTML</span>
<?= echo $this->foo ?>
<br />
In the source it displays like this:
<span>Blah blah HTML</span>
{$this->foo whatever it is} <br />
Instead of
<span>Blah blah HTML</span>
{$this->foo whatever it is}
<br />
Stuff like this happens all of the time. Inline PHP makes my new lines all wonky and it bothers me. It also happens when you start a full block of PHP within HTML but keep it consistent with the HTML tabbing. For example:
<div id="foo">
<div class="bar">
<?
foreach(whatever)
{
?>
</div>
</div>
Will mess up the formatting of the source and I have to do something like this:
<div id="foo">
<div class="bar">
<?
foreach(whatever)
{
?>
</div>
</div>
If you're worried about formatting of the html. Then you need to add a newline.
<span>Blah blah HTML</span>
<?= echo $this->foo."\n" ?>
<br />
But be careful, this is a dangerous route to go down. Because the next thing you'll worry about is tab indentation. So then you'll add a bunch of \t everywhere. And after a while your code will output a clean and neat html but will be close to unreadable as source code.
So my suggestion. Don't worry to much about it.
For the first question, you can just use the newline character \n
I am not so sure about the second item. May I ask why you are worried about the outputted html? If it is because you are using it to see what is output, may I introduce you to firebug? Firebug will display the DOM tree nice and clean for you (and even keeps it updated with DOM injections).
Just so you know, <?= actually means <?php echo. So you only have to do <?=$username?>
If you want your HTML output to be pretty and you don't want to rely on browser tools like firebug, PHP has a class called Tidy that will do the trick.
ps, short tags ( <?= ?> )have been deprecated. You might want to switch to ( <?php ?> )
View the generated HTML code with a tool, e.g. Firebug, that does formatting automatically.
After installing Firebug, just press the F12 key and select the HTML tab. You can navigate the HTML source using a tree control that pretty prints the markup.
You can use Firebug Lite if you are developing in a browser other than Firefox. Just inject the HTML snippet on the Firebug Lite webpage into your site.
Keep in mind that eliminating extraneous whitespace can improve the performance of your site, so having "minified" HTML isn't necessarily a bad thing.
Unfortunately there's not a lot you can do about it directly. While it's nice for us humans to view source code that's well indented, the HTML spec has always considered white space to be insignificant, and therefore people who develop systems for dealing with HTML often don't consider adding features for finely grained control. Also, PHP is made more flexible by the behavior you described. For example, if it was being used to generate output where white space WAS significant the behavior you described would be desirable.
If you decided that well indented HTML source code was important for you, you'd need to put a system in place around your output to handle the formatting. Rather than output directly, something would intercept your output and automatically handle the formatting for you. Output buffering is one was you could achieve this.
ob_start();
//...
//a bunch of code that echos or prints HTML
//...
$output = ob_get_clean();
echo some_function_or_method_call_to_format_your_html_however_you_want($output);
The implementation of some_function_or_method_call_to_format_your_html_however_you_want if left as an exercise for the reader, although the Tidy functions in PHP might be a good place to start.
There are other approaches you could take as well, for example routing all output through an object that, by context, could determine how many tabs or newline to add to the output. The main point is PHP, by itself, isn't going to help you solve this problem, but does provide you with the tools to build your own solution.
the PHP engine replaces areas with PHP code with nothing (except the output from inside php) so when you do:
<h1>Foo Bar</h1>
<?= $value; ?>
<p>my stuff</p>
php removes the newline after ?>. If you want that new line to "be preserved" you can just press enter 2 times after the closing ?>. Really though, if you need to produce HTML output that is "readable" to a human, you should use some library that cleans / sanitizes / formats HTML code (Tidy was mentioned above, so you could use that).
As for your formatting problems with PHP and preserving tabs, the explanation I just gave, covers it - but if you want to make more readable source code (for editing) you should consider using the PHP alternative syntax for templates (which is not really promoted nearly as well as it should be). Most all php control structures (for, while, foreach, if, else) have alternative syntax options which look much prettier in html templates.
<? foreach ($foo as $bar): ?>
<li>
<?= $bar['baz']; ?>
</li>
<? endforeach; ?>
<? if (false == empty($foo)): ?>
<p>
Hello World!
</p>
<? endif; ?>
<? for ($i = 0, $icount = count($foo); $i < $icount; $i++): $val = $foo[ $i ]; ?>
<tr>
<td><?= $val; ?></td>
</tr>
<? endfor; ?>
Also, someone above mentioned that the short tags in PHP are deprecated. That's just an outright falsehood, http://us.php.net/manual/en/ini.core.php#ini.short-open-tag - still alive, kicking, and just as awesome.
Short tags make the above code more readable than having <?php ?> everywhere, not to mention, it makes <?= ?> possible. <?= is the short hand for <?php echo or <? echo - making your code quite more readable. Though, it should be mentioned that if you're writing code that is supposed to be open source and used on a bevy of different webservers, you should at least warn your downloaders that you require short tags to be on (or turn it on via ini_set() or php_flag [in .htaccess])
Will mess up the formatting of the source and I have to do something like this:
<div id="foo">
<div class="bar">
<?
foreach(whatever)
{
?>
</div>
</div>
It's important that the original PHP source code is readable, so that you can maintain it easily. It's not at all important to make all the indenting pretty for the 0.0001% of people who will ‘view source’. The above snippet just makes things harder for you.
In the [HTML] source it displays like this:
<span>Blah blah HTML</span>
{$this->foo whatever it is} <br />
It doesn't for me, the newline appears where you expect. But even so, who cares? As long as the markup itself is valid and compact, you're fine.
Look at JimR's example using PHP in the style of well-nested start and end tags. This is a good approach to maintainability as it keeps one consistent hierarchy of code and markup, rather than switching between nested levels of indenting all the time.
For me, this also has the side-effect of giving HTML source with a consistent indent tree. It's one with more empty lines and larger indents than is strictly necessary, but again, who cares? Extra whitespace making the file bigger is not a problem; on-the-fly compression from the likes of mod_deflate will zip that away to nothing.
Note that the ‘alternative syntax’ as used by JimR is not necessary to use this technique, it works perfectly well with braces too and is a matter of personal taste which you choose:
<?php
$replyn= count($replies);
?>
<?php if ($replyn)==0) {?>
<p> (no replies.) </p>
<?php } else { ?>
<h3> Replies </h3>
<?php for ($i= 0; $i<$replyn; $i++) { ?>
<p>
<?php echo(htmlspecialchars($replies[$i], ENT_QUOTES)); ?>
</p>
<?php } ?>
<?php } ?>
(Although personally I use a shortcut function to avoid typing out echo(htmlspecialchars)) all the time. If you're not using htmlspecialchars, you've probably got security problems.)
This example uses full <?php tags so as to run whether or not short tags are allowed. Ultimately though I do agree with JimR that the full tags are, as they stand, a bit of a waste of time.
(It was a good idea to make PHP more compatible with XML's Processing Instructions, but since they never followed through with a way to template PHP tags into attribute values, it's still not really possible to author a PHP page that's also well-formed XML, making the exercise a bit pointless.)