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.
Related
This question already has answers here:
Is there harm in outputting html vs. using echo?
(4 answers)
Closed 5 years ago.
Is there a difference between this
<?php
myCode();
echo "Example";
?>
and
<?php
myCode();
?>
Example
this?
What is the best choice in terms of performance?
I've done a Benchmark printing 20000000 times "Example". I've executed the script from CLI, not through HTTP request (Centos 7 64bit).
Using "echo": 153.06723901367sec
Using HTML: 155.80555395508sec
For all pragmatic purposes, no, there is no relevant difference. Your script output will be "Example" in both cases. And in both cases, myCode() was executed before.
In fact, the OPCodes in both cases will be the same, because PHP will echo everything outside of <?php tags. It's basically just an implicit echo.
Technically, the way to the resulting OPCodes will be different, but this has no relevant impact on performance. Mostly anything outside <?php tags is treated as T_INLINE_HTML by the parser. This is then converted to an echo in the abstract syntax tree:
| T_INLINE_HTML { $$ = zend_ast_create(ZEND_AST_ECHO, $1); }
with ZEND_AST_ECHO being
case ZEND_AST_ECHO:
APPEND_NODE_1("echo");
However, your aim should be to separate logic from your views and templates as good as possible as it can easily lead to spaghetti code if you don't. As a rule of thumb, a function should not echo, but return strings. Most frameworks only echo once: at the end of a request when rendering the response.
Since you mentioned "Views" and MVC: a View in MVC is not necessarily a template, but a specific representation of a particular piece of data from the Model. It can be code that ultimately renders a template though. If that's what you want, you probably want to check out a template engine, like Twig (although PHP is a template engine on it's own).
Yes. The 1st is PHP, the 2nd is HTML.
In the first case you could do:
<?php
$var = 1;
echo "Example " . $var;
?>
The second case $var is undefined in the HTML so would be ignored.
<?php
$var = 1;
?>
Example $var
If you wanted to use that variable in the HTML you would need to go back into PHP i.e.
<?php echo $var; ?>
This is a preference thing in my experience, there are some pages that are mostly HTML that can be written that way. However, if I am writing PHP I prefer to stick with PHP and not bounce between the 2 languages. I don't know of anything that you can do in HTML that you can't produce from PHP. It makes for nasty looking code that is hard to debug.
Also there are issues with HTML headers (see PHP header() Function).
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.
What I want to do is pull html and PHP code out from a database and then execute it. So for example I may have:
<?php
$test = <<<END
<p> <?php
echo time();
?> </p>
END;
echo $test;
?>
What I want is to get $test to print
<p> 12:00PM </p> //right
instead of printing:
<p> <?php echo time(); ?> </p> //wrong
as occurs when I use the echo function.
Please do not tell me how to do the same thing with JavaScript or other work around. Instead stick to the question and remember the example is just an example to demonstrate my problem. The actual code is much more complicated.
I have looked at Javascript string variable that contains PHP code but none of the answers work.
Thanks,
Brett
I would strongly recommend against doing what you're asking to do. There are a number of very good reasons for this.
The answer to the question, as others have said, is to use eval(). However, eval() has several major issues with it.
Firstly, to follow-up from the comments on the question, code run through it is executed significantly slower than regular PHP code. Although PHP is a scripted language, it does have optimisations to make run faster. None of these optimisations work for an eval block, because the scripting engine can't know what the code will look like until it actually runs it.
Not only that, but loading the code from the database will also be slower than loading it from a file using a regular include() statement.
Secondly, eval() is one of the biggest security headaches you can have. An eval() statement will run any PHP code it is given, which means that an attacker can manipulate the code will be able to do anything on your server. In short, a single eval() statement in your code can turn a minor hack into a catastrophic one.
One alternative solution that doesn't involve changing your concept too much would be to save the PHP code to a file rather than the DB. This would allow you to simple include() it at the appropriate time, and would eliminate the speed issues discussed above. You could still use the DB to store it if you wished, and have it export to a cache file using a cron job or similar, or you could just save it directly to the file.
However, this solution wouldn't necessarily eliminate the security risks. You would still be running effectively arbitrary code, which would still mean that a hacker could do a lot of damage with a relatively simple hack.
I would therefore recommend re-thinking why you need to allow user-input PHP code to be entered into your software.
You can use eval() for this
$test = <<<END
<p> <?php
echo time();
?> </p>
END;
ob_start();
eval("?>$test");
$result = ob_get_clean();
Something like this might be useful...
<?php echo writedata($code_to_parse); ?>
<?php
function writedata($data){
if(substr($data,0,2)=="?>"){
eval($data);
// eval will run & echo the code immediately, so return an empty $code
$code="";
}else{
$code="$data";
}
return $code;
}
?>
Now you can handle either plain html & mixed php/html with one function call.
Sample data:
?>Bonjour. The time now is <?php echo $timenow; ?> in Paris.
<div class="bluebox">Perfect day for swimming</div>
There are some side effects using eval(), remember it will execute as soon as to call it, so can sometimes have unexpected results.
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
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);
}
?>