Print <<< END; question - php

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

Related

What are some good tips for writing php files along side raw html?

I do not like spitting back html with php's echo, makes it hard to do and read nested elements. So I usually write conditions that write raw html and make it as readable as possbile when editing the file directly or viewing the output html through the browser. However, I cannot find a style that stays readable for long. Any suggestions?
<?
if($foo == $bar)
{
?>
<div>
<p>hello, world</p>
</div>
<?
}
?>
As you can see, it doesn't look too good. At least not to me, but it makes the browser output more readable so I can better check the it for any mistakes.
i dont want this:
<?
if($foo == $bar)
{
echo "<div>\n\t<p>hello, world</p>\n</div>\n";
}
?>
Is my approach incorrect to begin with? should I use php to output to a .html file? and just view from the browser for mistakes and do as much php as possible inside the php file?
Your right it's not nice, instead use proper alternative syntax, for content with a large amount of HTML:
<?php if($foo == $bar): ?>
<div>
<p>hello, world</p>
</div>
<?php endif ?>
I don't believe you need a seperate template language to write maintainable code, PHP is perfectly fine in outputting variables in HTML.
Really the problem is seperating your logic from your output which a template engine can't help with if your not structuring your code properly in the first place. For example stuffing it all in an index.php file or not using MVC whereas you don't put HTML with your logic.
If you have a large project or are overly concerned with separating your PHP from your views, or you want the features which come with a template engine like built in caching and slots etc, then use one. But maybe first look at learning a framework which will improve your overall codebase as most frameworks come with their own. Though essentially you can achieve the same thing including nesting partials and blocks/slots with a 20 line view class which uses ob_* functions, which doesn't require you to learn a new syntax.
Rant over.. :s
Use a templating system like Smarty so you can separate your logic from your display code.It also allows you to bring in a designer that can work with html and might not know php at all. Smarty templates read more like HTML than PHP and that can make a big difference when dealing with a designer.
Ansered by #boatcoder
You can learn here
Without the use of templating engine, your best bet is #Lawrence's answer or this littly modified syntax of your first exemple (trimminig space and php tag) :
<? if($foo == $bar) { ?>
<div>
<p>hello, world</p>
</div>
<? } ?>

PHP/HTML output: echo vs return, output buffering, and syntax highlighting challenges

I prefer to write html outside of php tags, so eclipse can display the html with proper syntax highlighting. The concatenation method is harder to write and doesn't highlight (see the two examples below).
I apologize for the length. These examples are very simple, so it should be an easy read.
I DON'T like this, too many 'quotes' and $o's, and no syntax highlighting!:
<?php
display($something){
$o = '';
$o .= '<div>';
$o .= $something;
$o .= '</div>';
return $o;
}
// I want to be able to do this:
echo display(display('something'));
This gives a function the chance to finish the closing <tag> or even add additional html afterwards. The above example is functionally what I'm looking to do, but for these reasons ('quotes', $o's, and syntax highlighting) I haven't created a system like this.
The following example is how I prefer to write html, but I can't nest output, because it doesn't return!
<?php
function display($something){ ?>
<div>
<?=$something?>
</div>
<?php }
// I'd like to do this, but I can't
display(display('this doesn't return anything to the first function call...'));
This is where output buffering comes in, I'll get back to that in a second...
What I'm envisioning:
I'd like to be able to use func_get_args() to accomplish something like this (note, this will apply to OOP objects, just keeping it simple here):
<?php
some_panel( title_style_1('Sample Header'),
panel_content(you_tube($vid_id)),
small_img_frame($img_src) );
You'd basically be able to take any of these output functions and nest them any way you like. Just like you can put any <div> inside any <p> and vice versa. Only problem is, you have to make sure you close the tags... And, in this case, you could add any markup at the end or in between children.
This is where the output buffering comes in
<?php
function display($something){
ob_start(); // <---- Start buffer ?>
<div>
<?=$something?>
</div>
<?php return ob_end_clean(); // <------ Return output
}
// Now I can do this!!!
echo display(display('this should work!'));
And, drum roll please.... THE QUESTION:
If I'm repeatedly buffering potentially hundreds or even thousands of times per request, is this going to be a performance hit? I've read posts that warn against output buffering due to:
Reliability: If somewhere else a buffer was started, from what I read, it sounds like these nest and can potentially conflict.
Maintainability: If a buffer is started, you have to guarantee it will be stopped.
For my system, if output buffering is started and stopped in the same function call, these things seem to be OK. It's the excessive iteration of potentially 1000's of items that each start/stop output buffering for a single <li> that I'm worried about.
Also, if anyone knows of any frameworks or better ways to do what I'm trying to do, any suggestions would be appreciated!
How about nesting output via… output?
<?php
function foo($itemName) {
?>
<div class="item">
<?php bar($itemName); ?>
</div>
<?php
}
function bar($itemName) {
?>
<h1><?= $itemName ?></h1>
<p>Hello, world!</p>
<?php
}
?>
But to answer the rest of the question: benchmark it! Output buffering is usually not a problem, but it could very well be anybody’s bottleneck. It depends.
If you find yourself doing this sort of thing a lot, consider breaking it out in to several files or using a template system. Or not PHP.
Output buffering is probably a wash, it may even improve performance. The CPU wasted buffering is saved in doing less I/O. Socket writes are actually thousands of instructions. The only time it could become a problem is when the amount of output would adversely impact memory usage. And if you are buffering many megabytes of output you probably need to look into some form of streaming.
Here's an older post on this topic PHP output buffering - sounds like a bad idea, is it?

Opensource project's PHP syntax

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

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

php modes breaking out of php or not

I asked another question about HTML and PHP separation as I have seen references to it on tutorial and examples pages but I found that separation of HTML and PHP it something different than what people are actually commenting on and I think that is PHP modes.
That is breaking out of PHP or not. Should It be done? Is it important?
Is it just a matter of preference to echo my HTML output or should I break out to display it?
Example:
<?php
echo '<html'>;
?>
vs.
<?php
dostuff();
?>
<html>
<?
morestuff();
?>
I assume by "breaking out" you mean:
<?php foo(); ?>
test
<?php bar(); ?>
as opposed to
<?php
foo();
echo("test");
bar();
?>
Well, one advantage of the first solution is that your layout is still more or less readable in HTML editors. Also, it separates layout and logic, at least more than the other variant. It is probably also slightly faster than the second option because no strings need to be parsed and echo'ed. On the flipside, having tons and tons of individual PHP-blocks can really be hard to read because things that are semantically related are suddenly split. You can, of course, also combine both approaches.
I think the bottom line here is that as soon as you need to do so much formatting and echo'ing that the logic of your program becomes really obscured, you should consider using a 'real' template engine.
I think it depends on the situation.
how many lines do you want to echo to the browser?
do the lines contain $variable values? $array values?
do you loop trough a dataset? etc etc.
To me, it is more reable to just echo the lines most of the time.
<?php
if ( check($something) ) {
echo "Some variable is: $something<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
can be more readable than:
<?php
if ( check($something) ) {
?>
Some variable is: <?php echo $something; ?><br/>
<?php
} else {
?>
Some variable is something else!<br/>
<?php
}
?>
and with some IDEs (or stackoverflow.com syntaxhighlighting for example), it can even be more readable to use:
<?php
if ( check($something) ) {
echo 'Some variable is: '.$something."<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
In summary:
PHP offers you a lot of options to send content to your client.
The 'best method' differs from case tot case.
Choose the method that is most readable/maintainable and use it consistently.
If by breaking out you mean this sort of thing:
<?php
if($somecondition) {
?>
<!-- Some HTML -->
<?php
}
?>
Then yes, breaking out is better in most cases as it is more readable (many IDES highlight HTML syntax, and cannot do so if it is withing a string when being echo() ed)

Categories