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

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.

Related

Several <?php ?> blocks vs single one (semantics and functionality)

What I keep seeing is something like
<?php $page_title = ""; ?>
<?php include_once("inc/header.php"); /* Include Header */ ?>
versus
<?php
$page_title = "";
include_once("inc/header.php"); /* Include Header */
?>
I assume there is no difference in functionality (not sure however), but which way is more semantic / correct does it matter if you declare all your PHP in several PHP blocks or a single one? Is performance affected in any way?
This is a major reason why doing your PHP inline is going out of style. There's no performance hit that I know of. All <?php ?> does is tell the interpreter that this is to be processed by PHP so your first code block is saying
Stop parsing PHP
Start Parsing PHP
I would imagine there's some miniscule hit somewhere if you're trying to wring every last ounce of efficiency out but I consider it to be insignificant. It's important to userstand that if you're using opcode cache (and you should) then the only hit is on the parsing side. Repeated execution of cache will have 0 effect here.
Readability, however, really does demand your code be as compact as possible. Remember, someone may come behind you and work on this code. Having two blocks where only one is needed is inefficient.
There is no real answer to this.
Some people like to have it the "Code-Block"-Way and put it all in one set of tags, some other people prefer the "HTML-Tag"-Way where they put each command in a new set of tags
There is no difference in functionality except for the fact that everything between one ?> and the next <?php gets echo'ed (So you have a lot of spaces in your output HTML, which is okay, since they are ignored)
Performance might be affected, but in numbers you really don't need to care about.
Generally, if you are in templates (or lets say, PHTML, HTML and PHP mixed), try to keep all commands single-lined (Put all single commands in <?php ?> and on own lines), this will make it more readable between all those HTML tags.
If you don't have HTML in your PHP file, there is no reason to enclose all commands with PHP tags

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.

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

different ways of code writing. need suggestion

My friend writes everything using phps echo.
I mean he starts <? and echo everything, including header, main part, footer, he even has style.php file where he echos some css and then includes it in main project.
question is why is it better to do that way ? Or is it better at all?
Cause in dreamveawer everything is red. I mean it understands evrything as phps srtings and makes all text red.
If you do not use echo you have different colors in code and you can see where is ccs, javascript or html.
So what's better to write normally or I should try the same "echo everything" practice ?
No, it is no better to do that way.
Do not use echo to output HTML but divide your code into 2 parts - business logic part and presentation logic part, a latter one consists of mostly HTML with PHP used only to output data coming from the business logic part
a little example of such a template:
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
If that's how he does it, then please slap him across the back of the head for us please?
But seriously, there is this thing called MVC, please take a look at it, comprehend it, implement it and explain it to your friend.
That's horrendous.
You should try not to mix PHP and HTML if you can help it.
In some cases you will be interleaving some dynamic content with static content (and you could use a templating engine for that); but outputting the entire HTML document via PHP statements is a clear sign of insanity and sadism.
You might be interested in templates. They're not html nor php, but a combination between these two.
The advantage is that you can see/edit/update/maintain your code much easier, because the actual php part is somewhat separated from the html markup.
The main disadvantage is that it might be a bit slower, since php reads the template, makes replacements and then spits out the html.
Here's a link to some of the most used php template engines.
Using HTML code instead of echoing has the advantage that the editor (Dreamweaver in your case) can do syntax highlighting. This will help you find errors in your HTML faster.
Also, you don't have to think too much about escaping quotes in your HTML (you still need to think about proper escaping your PHP variables anyway).
I can think of several ways the bad habit of echoing everything can be formed:
Errors from missing PHP tags while intermingling PHP and HTML. For a newbie it takes a while to wrap your head around the concept of using one language (PHP) to write code in another language (HTML). I remember when I first learned PHP I thought it would be easier to echo everything instead of opening and closing PHP tags all the time.
Coming from a language background where every output must be printed explicitly.
Having read some insane micro-optimization article on the web that claims echoing is faster or more secure.

'echo' or drop out of 'programming' write HTML then start PHP code again

For the most part, when I want to display some HTML code to be actually rendered I would use a 'close PHP' tag, write the HTML, then open the PHP again. eg
<?php
// some php code
?>
<p>HTML that I want displayed</p>
<?php
// more php code
?>
But I have seen lots of people who would just use echo instead, so they would have done the above something like
<?php
// some php code
echo("<p>HTML that I want displayed</p>");
// more php code
?>
Is their any performance hit for dropping out and back in like that? I would assume not as the PHP engine would have to process the entire file either way.
What about when you use the echo function in the way that dose not look like a function, eg
echo "<p>HTML that I want displayed</p>"
I would hope that this is purely a matter of taste, but I would like to know if I was missing out on something. I personally find the first way preferable (dropping out of PHP then back in) as it helps draw a clear distinction between PHP and HTML and also lets you make use of code highlighting and hinting for your HTML, which is always handy.
The first type is preferable, exactly for the reasons you mentioned.
Actually, echoing out whole chunks of html is considered bad practice.
No, there's no performance increase that would be visible.
Sometimes its just simply easier to output content using echo (for example, when inside a while or for loop) than to close the php tag.
I think there's a preprocessor which converts the same form into the second. That's what happens in ASP.NET, anyway. And in both ASP.NET and classic ASP, loops can actually stretch across raw-HTML regions.
There's no performance difference at all.
Just the style that produces the most readable code. Depending on the actual situation that can be either of the two.
But mixing HTML and PHP should be avoided where possible anyway. THis can be accomplished by using a template system for your views.

Categories