PHP - To echo or not to echo? - php

What is more efficient and/or what is better practice, to echo the HTML or have many open and close php tags?
Obviously for big areas of HTML it is sensible to open and close the php tags. What about when dealing with something like generating XML? Should you open and close the php tags with a single echo for each piece of data or use a single echo with the XML tags included in quotations?

From a maintenance perspective, one should have the HTML / XML as separate from the code as possible IMO, so that minor changes can be made easily even by a non-technical person.
The more a homogeneous block the markup is, the cleaner the work.
One way to achieve this is to prepare as much as possible in variables, and using the heredoc syntax:
// Preparation
$var1 = get_value("yxyz");
$var2 = get_url ("abc");
$var3 = ($count = 0 ? "Count is zero" : "Count is not zero");
$var4 = htmlentities(get_value("def"));
// Output
echo <<<EOT
<fieldset title="$var4">
<ul class="$var1">
<li>
$var2
</li>
</ul>
</fieldset>
EOT;
You will want to use more sensible variable names, of course.
Edit: The link pointed out by #stesch in the comments provides some good arguments towards using a serializer when producing XML, and by extension, even HTML, instead of printing it out as shown above. I don't think a serializer is necessary in every situation, especially from a maintenance standpoint where templates are so much more easy to edit, but the link is well worth a read. HOWTO Avoid Being Called a Bozo When Producing XML
Another big advantage of the separation between logic and content is that if transition to a templating engine, or the introduction of caching becomes necessary one day, it's almost painless to implement because logic and code are already separated.

PHP solves this problem by what is known as heredocs. Check it out please.
Example:
echo <<<EOD
<td class="itemname">{$k}s</td>
<td class="price">{$v}/kg</td>
EOD;
Note: The heredoc identifer (EOD in this example) must not have any spaces or indentation.

Whichever makes sense to you. The performance difference is marginal, even if a large echo is faster.
But an echo of a big string is hard to read and more <?php echo $this->that; ?> tell a story :)

echo sends its argument further down the request processing chain, and eventually this string is sent to the client through a say, network socket. Depending on how the echo works in conjunction with underlying software layers (e.g. webserver), sometimes your script may be able to execute faster than it can push data to the client. Without output buffering, that is. With output buffering, you trade memory to gain speed - you echos are faster because they accumulate in a memory buffer. But only if there is no implicit buffering going on. One'll have to inspect Apache source code to see how does it treat PHPs stdout data.
That said, anything below is true for output buffering enabled scripts only, since without it the more data you attempt to push at once the longer you have to wait (the client has to receive and acknowledge it, by ways of TCP!).
It is more efficient to send a large string at once than do N echos concatenating output. By similar logic, it is more efficient for the interpreter to enter the PHP code block (PHP processing instruction in SGML/XML markup) once than enter and exit it many times.
As for me, I assemble my markup not with echo, but using XML DOM API. This is also in accordance with the article linked above. (I reprint the link: http://hsivonen.iki.fi/producing-xml/) This also answers the question whether to use one or many PHP tags. Use one tag which is your entire script, let it assemble the resulting markup and send it to the client.

Personally I tend to prefer what looks the best as code readability is very important, particularly in a team environment. In terms of best practice I'm afraid I'm not certain however it is usually best practice to optimize last meaning that you should write it for readability first and then if you encounter speed issues do some refactoring.
Any issues you have with efficiency are likely to be elsewhere in your code unless you are doing millions of echo's.
Another thing to consider is the use of an MVC to separate your "views" from all of your business logic which is a very clean way to code. Using a template framework such as smarty can take this one step further leading to epic win.

Whatever you do, don't print XML!
See HOWTO Avoid Being Called a Bozo When Producing XML

I've made myself the same question long time ago and came up with the same answer, it's not a considerable difference. I deduct this answer with this test:
<?
header('content-type:text/plain');
for ($i=0; $i<10; $i++) {
$r = benchmark_functions(
array('output_embeed','output_single_quote','output_double_quote'),
10000);
var_dump($r);
}
function output_embeed($i) {
?>test <?php echo $i; ?> :)<?
}
function output_single_quote($i) {
echo 'test '.$i.' :)';
}
function output_double_quote($i) {
echo "test $i :)";
}
function benchmark_functions($functions, $amount=1000) {
if (!is_array($functions)||!$functions)
return(false);
$result = array();
foreach ($functions as $function)
if (!function_exists($function))
return(false);
ob_start();
foreach ($functions as $idx=>$function) {
$start = microtime(true);
for ($i=0;$i<$amount;$i++) {
$function($idx);
}
$time = microtime(true) - $start;
$result[$idx.'_'.$function] = $time;
}
ob_end_clean();
return($result);
}
?>

Related

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?

Direct HTML or PHP generated html

What is better / faster:
For example:
STATIC / direct HTML:
<?php
for($i=0;$i<$sth;$i++) {
?>
<tr>
<td>
<?php echo $content; ?>
</td>
</tr>
<?php
}
?>
OR
PHP generated HTML:
<?php
for($i=0;$i<$sth;$i++) {
echo "<tr><td>".$content."</td></tr>";
}
?>
Does it matter which option i choose?
Thanks
It's not so much a matter of speed which may vary based on use case, but of making the code clean and maintainable. Actually both examples make for code that's hard to maintain and read.
I'd suggest using a simple and lightweight templating engine to separate all logic from presentation.
I think that there is no substantial difference between the two, the question should be "Which one is more readable" IMHO and i think that using php and html inline is far less readable than echoing php. But that's just my idea.
The better: Generated html.
Generated html with php is far more easy to maintain and easier to read.
The faster: There is no significant speed difference. However on large dynamic websites where content is loaded from a database etc things might take a fraction of a second more time to output. However, the time you spend on updating a static html file is a lot more than editing dynamic content..
Go dynamic :]
In this case "PHP generated HTML" would be quicker because you are only doing one echo where as in "STATIC / direct HTML" you are doing $sth echos. If $sth is zero then "STATIC / direct HTML" would be quicker.
But seriously, the page is parsed and optimised/normalised so it doesn't make any difference. Parsing with less might be quicker because there are less context switches but this is the smallest part (compared to running it) so it makes negligible difference.
Just pick the style that you feel comfortable with.
Two codes represent the same thing, not differentiate in the speed , But the second code may be a little faster because the code does not contain more than one entry and exit signs.
<?php ?>
this will be carried out faster .
The first approach should be faster as it does not involve a lot of string concatenation. It's also better in terms of code readability.
I think the first solution:
It is clearer and do not require php elaborations with string to dispplay simple static content

PHP library for HTML output

Is there an standard output library that "knows" that php outputs to html?
For instance:
var_dump - this should be wrapped in <pre> or maybe in a table if the variable is an array
a version of echo that adds a "<br/>\n" in the end
Somewhere in the middle of PHPcode I want to add an H3 title:
.
?><h3><?= $title ?></h3><?
Out of php and then back in. I'd rather write:
tag_wrap($title, 'h3');
or
h3($title);
Obviously I can write a library myself, but I would prefer to use a conventional way if there is one.
Edit
3 Might not be a good example - I don't get much for using alternative syntax and I could have made it shorter.
1 and 2 are useful for debugging and quick testing.
I doubt that anyone would murder me for using some high-level html emitting functions of my own making when it saves a lot of writing.
In regards to #1, try xdebug's var_dump override, if you control your server and can install PHP extensions. The remote debugger and performance tools provided by xdebug are great additions to your arsenal. If you're looking only for pure PHP code, consider Kint or dBug to supplement var_dump.
In regards to #2 and #3, you don't need to do this. Rather, you probably shouldn't do this.
PHP makes a fine HTML templating language. Trying to create functions to emit HTML is going to lead you down a horrible road of basically implementing the DOM in a horribly awkward and backwards way. Considering how horribly awkward the DOM already is, that'll be quite an accomplishment. The future maintainers of your code are going to want to murder you for it.
There is no shame in escaping out of PHP to emit large blocks of HTML. Escaping out to emit a single tag, though, is completely silly. Don't do that, and don't create functions that do that. There are better ways.
First, don't forget that print and echo aren't functions, they're built in to the language parser. Because they're special snowflakes, they can take a list without parens. This can make some awkward HTML construction far less awkward. For example:
echo '<select name="', htmlspecialchars($select_name), '</select>';
foreach($list as $key => $value) {
echo '<option value="',
htmlspecialchars($key),
'">',
htmlspecialchars($value),
'</option>'
}
echo '</select>';
Next, PHP supports heredocs, a method of creating a double-quoted string without the double-quotes:
$snippet = <<<HERE
<h1>$heading</h1>
<p>
<span class="aside">$aside_content</span>
$actual_content
</p>
HERE;
With these two tools in your arsenal, you may find yourself breaking out of PHP far less frequently.
While there is a case for helper functions (there are only so many ways you can build a <select>, for example), you want to use these carefully and create them to reduce copy and paste, not simply to create them. The people that will be taking care of the code you're writing five years from now will appreciate you for it.
You should use a php template engine and just separate the entire presentation and logic. It make no sense for a educated programmer to try to create a library like that.

Performance difference between these methods

Is there any advantages/disadvantages to either of these statements over the other one:
<?php
$test = 1;
$test2 = 2;
$test3 = $test + $test2;
echo "<p>Hello World</p>";
?>
OR
<?php
$test = 1;
$test2 = 2;
$test3 = $test + $test2;
?>
<p>Hello World</p>
What i'm asking is, if i'm outputting a page using PHP should i keep closing the php tags and stick normal HTML in or echo out the HTML? Which is better?
if you want do be realy exact, there are three options:
the slowest:
echo "<p>Hello World</p>";
a bit faster (no need to check for inline-valiables because of single quotes):
echo '<p>Hello World</p>';
the fastest (no php-interpreting at all):
<p>Hello World</p>
but between all of this, the difference would be so minimalistic that you won't ever notice it - much more important: make your code redable and do it the same way everywhere, so nobody who's reading your code (and has to maintain it) gets confused. i personally would prefer the third method (so i can use code-completition in my IDE), but it's your choice - i know a lot of people who output everything using echo.
EDIT: to be complete, there are some more possibilitys i didn't mentioned like heredoc- and nowdoc-syntax, but this are basically the same as double/single-quotes... also, you could write print instead of echo and so on, but that wouldn't make a difference.
Method 2 is cleaner IMHO because you separate PHP code from HTML. Your IDE (if you use any) can parse your HTML tags and autocomplete them, and spot any typo's.
I'm not a PHP programmer but I would assume the 2nd method is faster, because PHP doesn't have to process the echo language construct, allocate buffer and all that stuff. It is also cleaner, and less of a hassle to modify the HTML.
Also, it would be wise to learn to use a template engine for your HTML in order to separate concerns. Smarty was popular a couple years ago, I don't know if it's still is.
Although the difference is negligible, you should stick normal outputing out of PHP tags. Echo command will have to be parsed by PHP interpreter and then sent as output.
The only difference is that with echo(); you instruct PHP to process the code, otherwise, there is no difference at all.
One way or another, the result is exactly the same and for performance, there is almost no differences at all. Like... How much time PHP needs to process that echo();? I think with miliseconds you could run in problems calculating numbers that small. Hehe.

Should one use PHP to print all of a page's HTML?

So I've always developed PHP pages like this: <?php goes at the top, ?> goes at the bottom, and all the HTML gets either print()ed or echo()ed out. Is that slower than having non-dynamic html outputted outside of <?php ?> tags? I can't seem to find any info about this.
Thanks!
--Mala
UPDATE: the consesus seems to be on doing it my old way being hard to read. This is not the case if you break your strings up line by line as in:
print("\n".
"first line goes here\n".
"second line goes here\n".
"third line");
etc. It actually makes it a lot easier to read than having html outside of php structures, as this way everything is properly indented. That being said, it involves a lot of string concatenation.
I'm not sure about speed, but it's typically best practice to separate dynamic elements and the display of them.
Check out a framework like CodeIgniter: This has a "controller" and a "model" that grab data, sort it or do whatever you like with it, and then feed it to a "view" (some sort of template).
This paradigm is called MVC, and is a really, really valuable thing to learn about. I've found its chief advantage to be easier-to-maintain code. I don't end up with a monster document that I have to re-learn each time I approach it.
Resources:
CodeIgniter
MVC
The difference in speed is probably negligible, however, when **print()**ing out all of your HTML with PHP, the code can get very ugly, and makes it much harder to read than if you just have plain HTML.
Edit: Also, if you're are **print()**ing out static HTML that doesn't change, really what is the point? It gives you no added benefit.
Pros
None that I can see
Cons
Code that is hard to read
One more step in processing for the PHP engine, which although probably not noticeable, it is an extra step.
The speed is negligible - trust me, this will not be your bottleneck.
Along with any other MVC framework, you might want to check out a simple templating system, such as Smarty, which separates your PHP logic from your HTML and also does caching.
I don't know if it's slower or faster, but (in my opinion) it makes the code a lot more difficult to understand. Which I guess is why I don't typically do it.
It is almost the same from a performance point of view.
I would set the focus on the readability of the code. If you have a performance problem, figure out the bottleneck and cache it.
Is that slower than having non-dynamic html outputted outside of <?php ?> tags?
Well yes, it is... marginally. But that's not really the issue: it's all about the readability.
this way everything is properly indented
Your example isn't indented at all, which is fairly typical for the print-heavy, PHP I've unfortunately had to maintain!
Try this approach to keeping good, consistent indentation:
<ul>
<?php
// block of arbitrary code blah blah
//
$conditions= get_conditions_from_request();
$isadmin= $user->privileges>=PRIV_ADMIN;
?>
<?php foreach (select_things($conditions) as $thing) { ?>
<li>
<strong><?php h($thing->title); ?></strong>
<?php if ($isadmin) { ?>
<a href="/editthing.php?id=<?php u($thing->id); ?> (Edit) </a>
<?php } ?>
<?php h($thing->description); ?>
</li>
<?php } ?>
</ul>
(This presumes a function h that calls echo htmlspecialchars and u that does echo htmlspecialchars urlencode. Getting this escaping stuff right is essential to having a secure site, and is something that's almost always wrong in print-based PHP, as it tends to use "blah $var blah"-style templating without any escaping at all.)
Maybe not the best practice, but I choose to mix and match print() statements. For large chunks of layout code, I don't use print(), but if I'm rendering a complex if/else or for/while block and I'd be exiting the PHP block every other word, then I'll print out the non-dynamic text with the dynamic text.
Performance is very negligible at best. You can create a page, and put a timer on it. (Here is a tutorial on creating a script timer)
Output the exact same data both ways, and measure it with as many samplings as you can get, this should roughly tell you which is faster. I'm guessing very close to the same.
I have seen a lot of these pages with PHP embedded inside HTML, and I don't like it. As Alex Mcp suggested you should be thinking about a MVC model.
The problem with scripts embedded into html is the flow control and logic aren't easy to read, and there are some wierd problems that occur here and there. The best solution for me is usually to use Smarty or the Zend Framework to create template pages and then swap the data that goes in and out. Much easier to manage in the long run.

Categories