What is the pro and cons using Heredoc Notation in your PHP? - php

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....

Related

Why should we separate PHP from HTML

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.

Print <<< END; question

Okay, so I have a question. I use print <<< END followed by an END; after my html and variables instead of echo and print. I use this because it doesn't seem to have an effect on speed and the code just looks more organized in my opinion. I'm sure others will disagree but it's just my opinion.
I have a current project and that's the primary method I use to output HTML. No problems so far.
What are the disadvantages to using this? I have spoken with coders about it before, but they never really give me a reason not to use it just to not use it. I would appreciate any advice on this because I haven't had any problems with it.
The syntax you're describing is called a heredoc. As far as I know there is no performance difference between using heredocs and single- / double-quoted strings.
Heredocs can often help to prevent syntax errors, because there is no need to escape ' and " within the string. Another option would be to jump out of PHP into plain HTML, which requires no echo calls whatsoever:
<?php
... do things ...
?>
<div id="result"><?php var_dump($result); ?></div>
<?php
... do more things ...
?>
The only disadvantage i can think of is its harder to read for developers. This too is opinion but i find it much easier to read alternate syntax in template files, i.e.:
<?php if($something): ?>
<div id="something">
<?php echo $something->text ?>
</div>
<?php endif; ?>
And switching in and out like this is the only reason i can see to use heredoc as far as html is concerned. IF you have functions that are outputting massive amounts of html then you should change those to include a file in some manner. IE. you shoudl need to switch in and out of html except in your view, and those views should be separate completely form your functions or models. for exampl you should be doing:
function getSomething($var){
if($var){
$html = <<< HTML
<div id="something">
$var->text
</div>
HTML;
}
}
This is obvioulsy a simle example and actually this example isnt so bad, but if the HTML is more complex it starts to get jsut ugly. And in the case of methods on model classes its just plain evil no matter how simple the HTML is. Id prefer something like the following:
getSomething($var, $template = 'something.php')
{
if($var){
ob_start();
include($template); // $var is accessible in something.php
return ob_get_clean();
}
return null;
}
Of course the include will result in slight a performance hit but thats where caching comes in :-)

Errors with basic PHP template using eval()

I'm just about ready to cry. I have read the php.net manual page, tried a dozen Google searches with various phrases, and scanned hundreds of stackoverflow threads. I have seen this method in use, but it just doesn't work for me. It seems so basic. I have a couple related questions or problems I don't know how to find answers to.
The important part of the PHP file looks like this:
switch() {
…other cases…
default:
$tpl['title'] = "Newsletter Signup";
$tpl['description'] = "Newsletter description";
$tpl['page-content'] = file_get_contents('signup.html');
}
$tpl_src = addslashes(file_get_contents('index.tpl'));
eval("\$html = \"$tpl_src\";");
echo $html;
My index.tpl file includes lines like these:
<title>{$tpl['title']}</title>
<meta name="description" content="{$tpl['description']}" />
nav, etc…
<div id="main-content"> {$tpl['page-content']} </div>
I like how neat and clean the code is, without a whole bunch of extra <?=…?>'s.
First, when curly brackets {} appear in a string, what is that called? I might be able to look it up and learn how to use them if I knew.
Next, this just doesn't work at all. If I remove the single quotes from the variable keys, it's good, but php.net says you should never do that in case my name becomes a language constant at some point. Fair enough. But how do I fix this? I like using an array for the vars in case I want to build an evalTemplate subroutine and can just pass $tpl to it.
Lastly, $tpl['page-content'] doesn't print out. The variable is set okay; I can use echo $tpl['page-content'] to test, but it appears as a single blank line in the final HTML.
I'm sure there's just some aspect of the language I don't know yet. Any help is much appreciated!!
As Volker pointed out, addslashes seems to be an issue. Try addcslashes instead. Also, I'd strongly recommend making this a function, to simplify sanitisation / parsing:
function render ($file, $vars)
{
// .. extra sanitisation, validation, et al.
$_html = '';
$_raw_file = addcslashes (file_get_contents ($file), '"\\');
extract ($vars, EXTR_SKIP);
eval ('$_html = "'.$_raw_file.'"');
return $_html;
}
And called thus:
switch() {
// …other cases…
default:
$tpl['title'] = "Newsletter Signup";
$tpl['description'] = "Newsletter description";
$tpl['page-content'] = render ('signup.html');
}
echo render ('index.tpl', $tpl);
PS: The use of extract above means that your vars will simply be $title, not $tpl['title'], etc.
Usually you don't use the '' string delimiters in string variable expansion. I.e. "$tpl[content]" instead of "$tpl['content']".
As for as the braces, they delimit variable's when identifier characters may come straight before or after the name. For example:
$item = "Cup";
$text = "I smashed four $items"; // won't work
$text = "I smashed four {$item}s"; // will work.
// 2nd output: "I smashed four Cups"
addslashes() adds slashes before both single- and double-quotes within the string.
The code generated for your example would be
$html = "<title>{$tpl[\'title\']}</title>
<meta name=\"description\" content=\"{$tpl[\'description\']}\" />
nav, etc…¦
<div id=\"main-content\"> {$tpl[\'page-content\']} </div>";
And {$tpl[\'title\']} doesn't parse well.

How do you prevent inline <?= text ?> statement from messing up the displayed source code?

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

Escape HTML to PHP or Use Echo? Which is better?

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.

Categories