Echoing HTML within your PHP - php

This is more of a wondering than a technical question and Im sorry if this questions seems daft or the answer is obvious to some but I was wondering...
Is it better to always echo out any HTML you need to write or to close the PHP tags when you need to write HTML and re-open again after? essentially embedding the PHP within the HTML?
Here is an example of each:
for($x=0;$x<count($customers);$x++)
{
echo '<tr>';
echo '<td><a class=summary href=mailto:'.$customers[$x]["Email"].'>'.$customers[$x]["Email"].'</td>';
echo '<td>'.$customers[$x]["Title"].'</td>';
echo '<td>'.$customers[$x]["FirstName"].'</td>';
echo '<td>'.$customers[$x]["Surname"].'</td>';
echo '<td>'.$customers[$x]["DeliveryCountryID"].'</td>';
echo '<td>'.$customers[$x]["LanguageID"].'</td>';
echo '</tr>';
}
that shows ALL HTML being echo'd
<?php
for($x=0;$x<count($customers);$x++)
{
?>
<tr>
<td><?=$customers[$x]["Email"]?></td>
<td><?=$customers[$x]["Title"]?></td>
<td><?=$customers[$x]["FirstName"]?></td>
<td><?=$customers[$x]["Surname"]?></td>
<td><?=$customers[$x]["DeliveryCountryID"]?></td>
<td><?=$customers[$x]["LanguageID"]?></td>
</tr>
<?php
}
?>
there is the example of embedding PHP within the HTML.
The reason I ask is because i'm at the start of my programming career I'm low on experience and Ive joined a company where their old developer, obviously more experienced than myself echo'd EVERYTHING out.
I have never done it this way as I like to embed PHP into my HTML and I find his code difficult to read sometimes.
Is there a reason he did it this way or is that the best way or would it be worth me slowly changing the code to be more like how I tend to do things?

The best way would be to use a template engine such as Smarty and separate your business logic and presentation. This gives you more flexibility on your code.
In your case I would prefer the second approach ("<td><?=$customers[$x]["Email"]?></td>") as it is easy to read and understand. This also has two more advantages,
if you have someone else working on the application such as a designer, making changes will be easier for him.
In future if you decide to use to a template engine you can easily convert your code.

First ask yourself what "better" means.
If "better" is something that is more readable, you can face the following problems:
In HTML code, if there are some <?php echo $var[attr]; ?> you can easily miss them.
In PHP code if there are lots of echo '<tr><td ............................ '; you can have problems with understanding what's inside, especially if you have lots of escaped characters. You have to add a newline character.
My answer: it depends what is more important to you: HTML? use 1. PHP? use 2.
If "better" is something faster, than use 1. Less to parse is less time-consuming. But does this time really matter?
If "better" is something shorter and less memory-consuming, the HTML files have less text. But does those bytes really matter?
Anyway, I always avoid merging both two methods, for example:
<div>
<p>Some text....</p>
<!-- some other stuff like lots of form fields -->
<?php
// some php code
echo '</div>';
That's because in IDEs you can easier find errors like unclosed tags if it does not look into PHP.

This is personal preference, but the practice I've seen most common is to have the HTML be the base and insert the PHP where necessary. As someone else stated, separate your business logic from your presentation. Use a separate directory for functions or your code-behind, then at the beginning of your document do an include_once. That way your presentation code is fairly straightforward HTML (usually easier for designers to handle), and the PHP is used to insert what is needed.
This is especially helpful when PHP is being used like a CMS or using database-driven web content. Whenever possible, separate your logic from your presentation.

There are many ways to echo'd your code. and you can't consider that this is the best way.
all things is depend on you. what you like? on my way I like to embed PHP in HTML (second approach). but may be other like echo'd all HTML code in php.
The whole thing is depend on you. what you choose. all are same

Related

PHP good practices - Echo usage

I've programmed for many years now in c++/c/python but never did a project in PHP, which I will be doing soon.
1- I find the usage of echo to be somewhat annoying, especially for printing long stuff. For example, if I have a function which wants to echo a redundant part of a website, such as the header or a nav menu, what approach would be better.
<?php
function PrintHeader() {
[some php stuff, mysql queries, etc]
?>
some HTML code
more HTML code
<?php
[some closing php stuff]
}
?>
Is it better than
<?php
function PrintHeader() {
[some php stuff, mysql queries, etc]
echo 'some HTML code'
echo 'more HTML code'
[some closing php stuff]
}
?>
I find somewhat the first approach to be, to me, simpler, because you can modify the HTML code more easily without the echos. I tested it, it works, but is it a good approach? Is it valid?
2- Is it considered a good programming practice to use a function to echo a redundant part of a website, rather than copy/pasting the redundant code accross all PHP files?
These questions might sound obvious to some, but I have not much experience about code management in PHP. I always liked to reduce code redundancy as much as possible; it's easier to maintain.
Traditionally, this kind of thing is achieved in PHP by "requiring" a file that contains the content you need. e.g.
header.php:
<div>some html</div>
Your main file:
<?php
require 'header.php';
?>
This removes much of the need to embed HTML within your PHP. However, a more modern approach is to use a templating language, which allows you to house your HTML, along with simple display logic like branching and loops, outside of your PHP code entirely. Have a look at http://www.phptherightway.com/#templating for some more advice on both approaches. I'd strongly recommend you read all of phptherightway.com, in fact - it doesn't take long and will probably answer a lot of other questions you might have.
first of all, nowadays people often use template files which are later parsed by PHP. Often are template languages like Twig for example used.
its more user preference in my opinion, but I definetly prefer the 1st variant because its a lot more readable :).
You should definetly put redundant parts of your website into a template and just include it if you need it :).

Writing HTML inside echos VS Writing HTML Between PHP tags

In Between PHP Tags
if(condition){
?>
<!-- HTML here -->
<?
}
In Echos
if(condition){
echo "HTML here";
}
I use above two methods in my code. But I'm wondering which one is the industry standard and good for performance? Are there any pros and cons of above methods? Which method should I use? and Why?
Since I'm new to PHP I hope you guys will help me out to figure this out. Thanks
Best industry practice is normally to keep your HTML and your PHP completely seperate (see http://www.smarty.net/ as an example of a templating system)
However, you might find your editor will do nicer syntax highlighting if you don't put your HTML in echos
Personal preference based upon readability. Choose whichever will be easier for someone else reading your code (or you in the future) to understand.
Typically speaking though, if it is a lot of HTML you wouldn't want to put it inside a PHP echo, and if it's short you would. Think of the former as a template, and the latter as a method that returns an HTML snippet.

what is the recommended way to embed html codes inside php codes?

Lets say I have 2 cases:
<?php
print("html code goes here");
?>
v.s
<?php
?>
html codes goes here
<?php
?>
Would the performance for PHP interpreter in the first case be worse than the second one? (Due to the extra overhead of processing inside print function).
So, does anyone have a recommended way to insert html codes inside php codes?
Oh, for the sake of all those who edit your code later, please never put any significant amount HTML code inside a string and echo it out. In any language.
HTML belongs in HTML files, formatted and styled by your IDE or editor, so it can be read. Giant string blocks are the biggest cause of HTML errors I have ever seen.
Performance shouldn't matter too much, in this case, but I would assume the second would be faster, because it is streamed directly to the output or buffer.
If you want it to be easier to read, enable short tags, and write it like this:
?><b>blah blah blah</b><?
Plus, with short tags enabled, it's easier to echo out variables:
Hello, <?= $username ?>
If you are using this to generate some sort of reusable library, there are other options.
You should put HTML outside of PHP code in order for better maintenance and scalability. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
Rather then try to think about constantly separating your php and HTML you should instead be in the mind set of separating your backend logic and display logic.
The MVC pattern is a good way of thinking about your code - In order to correctly use PHP you must use MVC (model-view-controller) pattern
Never put HTML inside PHP codes unless you specifically intend to do so or its very small. But then again 100% separation is what i recommend. People will have to work very hard to understand your code later if you mix them up. Especially designers who may not be comfortable with php.
The golden rule is separation of the front and back end process to the maximum helps in every aspect. Keep things where they belong. Styles in CSS, Java-scripts in JS, Php in a library folder/files and just use the required classes/functions.
Use short tags <? if required (but i dont like it :P ) also <?= tag for output echo. Besides short tags are better be avoided.
Don't do it that way at all! 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.
Also, you don't have to worry about your designer messing with your code while doing a find/replace!
Better yet would be to go to a setup like Django or Rails that has clearly delineated code/template setup, but if you can't do that (cheap hosting solutions) then at least use templating. I don't know if smarty is the best thing for PHP, but its far better than both solutions you are proposing.
[head above the parapet] Many of us have learnt templating from WordPress where without embedding php it's virtually impossible to do anything. I can quite understand why people advocate strict MVC or engines such as Smarty but the fact is in the case of WordPress development you need to manipulate output on the fly with php. In fact, coming from that background, I always use to assume that the 'hp' in php was for exactly that reason. So I could write 'normal' looking HTML, do a bit of server-side processing and then return to HTML.
So, from my point of view, the answer to your question, is the second of your examples is much easier to read - one of the fundamentals of elegant coding. But it does depend. If there's a lot of processing to produce a simple piece of html then it may be easier to build a large variable and echo it at the end. I abhore multiple lines of echo statements. In this case I am likely to use a function to keep my HMTL clean. Again WordPress does this a lot; for instance the_title() returns a simple string but does a deal of processing before returning this string so <h1><? the_title(); ?> </h1> reads well.
That is the POV of a WordPress developer who was never formally taught complex coding. I expect to lose a fair amount of reputation points over this answer. [/head above the parapet]

Is it a bad practice to write HTML markup using only PHP echo statements?

There is a guy at work that pretty much writes all of his html markup by using echo statements. It looks really clean and I like it a lot, but I remember hearing it is a bad practice considering it becomes a little much when you have to write large quantities of markup. What is the best practice?
Alright given the answers, I felt I should put in my 2 cents.
First up, it depends on the project. Me, personally, I use PHP as my template engine, and not a 3rd party. So I store my view logic in a "template" which is just php markup, which does use a few echos, but the echo statements just echo relevant data and not html code. Breaking in and out of PHP is not bad practice, if done correctly.
Having said that, it is much easier to manipulate HTML in a "template" file where the HTML is on it's own without having to worry about quotes (I know heredoc solves this problem, but it is kind of hard to do a foreach loop inside of a heredoc to display data). So my suggestion is just make a template folder / file for your view logic and use the short open tags, if you want to enable them / risk a client not having them enabled or use the <?php echo $data; ?> to echo out your data in that file and include it when needed.
Sorry if this sounds confusing. But that is my preferred method, as having 10 echos that just display data vs 100 echos that display html and data looks nicer and is easier to maneuver / debug in my opinion.
Unless you have hundreds of lines of markup, I think that this is a micro-optimization. That is to say that a HEREDOC, echo, print, or between PHP tags doesn't really matter.
In the end, it boils down to what's easiest for you or your team to maintain.
This is not necessaryly bad practice. As long is your code is readable, do it this way.
If your project grows larger I might however suggest using a template engine (for example smarty.net).
I always read/heard that it's more efficient to throw out markup from PHP than to switch into and out of the preprocessor.
After all, that's what HEREDOCs are for. A TON of echo statements in a row is probably not as good a plan as one on a larger string.
I think the best practice is to simplify your code. If you have a large number of the Echo statements that can possibly be reused pull them out into a separate PHP file and use php require statement to include that common code so the main file you are looking at is simpler. Even if the can't be reused, but that they are static and should not change, pull them out. No need to clutter you page with information that is just noise.
I have all my html code inside different echo's and I find no problem whatsoever with it.
It sounds like a bad practice if you consider that someday you might want to change technologies (like from php to asp.net or ruby on rails). Seems like Seperation of Concerns is thrown out the window.

separating php and html... why?

So I have seen some comments on various web sites, pages, and questions I have asked about separating php and html.
I assume this means doing this:
<?php
myPhpStuff();
?>
<html>
<?php
morePhpStuff();
?>
Rather than:
<?php
doPhpStuff();
echo '<html>';
?>
But why does this matter? Is it really important to do or is it a preference?
Also it seems like when I started using PHP doing something like breaking out of PHP in a while loop would cause errors. Perhaps this is not true anymore or never was.
I made a small example with this concept but to me it seems so messy:
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
?>
<b>Fatty has </b><?php echo $cookies; ?> <b>cookies left.</b><br>
<?php
}
?>
Are there instances when it is just better to have the HTML inside the PHP?
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
echo'<b>Fatty has </b> '.$cookies.' <b>cookies left.</b><br>';
}
?>
When people talk about separating PHP and HTML they are probably referring to the practice of separating a website's presentation from the code that is used to generate it.
For example, say you had a DVD rental website and on the homepage you showed a list of available DVDs. You need to do several things: get DVD data from a database, extract and/or format that data and maybe mix some data from several tables. format it for output, combine the DVD data with HTML to create the webpage the user is going to see in their browser.
It is good practice to separate the HTML generation from the rest of the code, this means you can easily change your HTML output (presentation) without having to change the business logic (the reading and manipulation of data). And the opposite is true, you can change your logic, or even your database, without having to change your HTML.
A common pattern for this is called MVC (model view controller).
You might also want to look at the Smarty library - it's a widely used PHP library for separating presentation and logic.
Let's make it clear what is not separation
you switch from php mode to html mode
you use print or echo statements to write out html code
you use small php snipplets inside html files
If you do this, there is no separation at all, no matter if you escape from php to html blocks or do it the other way and put php code into html.
Have a look at a good templating engine, there are a plenty of reasons in the "why use ...." parts of the manuals. I'd suggert www.smarty.net especially http://www.smarty.net/whyuse.php
It will answer all your questions now you have.
It is very important to separate application logic from presentation logic in projects. The benefits include:
Readability: Your code will be much easier to read if it does not mix PHP and HTML. Also, HTML can become difficult to read if its stored and escaped in PHP strings.
Reusability: If you hard-code HTML strings within PHP code, the code will be very specifc to your project and it won't be possible to reuse your code in later projects. On the other hand, if you write small functions that do one task at a time, and put HTML into separate template files, reusing your code in future projects will be possible and much easier.
Working in a team: If you are working in a team that contains developers and designers, separation of application logic and presentation templates will be advantageous to both. Developers will be able to work on the application without worrying about the presentation, and designers (who don't necessarily know PHP very will) will be able to create and update templates without messing with PHP code.
for pages that contain a lot of HTML, embedding PHP code into the page could be easier. this is one of the first intentions behind PHP. anyway when you are developing an application with lots and lots of logic, different types of connectivity, data manipulation, ... your PHP code gets too complicated if you want to just embed them in the same pages that are shown to users. and then the story of maintenance begins. how are you going to change something in the code, fix a bug, add a new feature?
the best way is to separate your logic (where most of the code is PHP) in different files (even directories) from your page files (where most of the code is HTML, XML, CSV, ...).
this has been a concern for developers for so many years and there are recommendations to handle these general problems, that are called design patterns.
since not everyone has the experience, and can apply these design patterns into his application, some experienced developers create Frameworks, that will help other developers to use all the knowledge and experience laying in the hear of that framework.
when you look at toady's most used PHP frameworks, you see that all of them put code into PHP Classes in special directories, make configurations, and .... in none of these files you see a line of HTML. but there are special files that are used to show the results to users, and they have a lot of HTML, so you can embed your PHP values inside those HTML pages to show to users. but remember that these values are not calculated on the same page, they are results of a lot of other PHP codes, written in other PHP files that have no HTML in them.
I find it preferable to separate application logic from the view file (done well with CodeIgniter framework with MVC) as it leaves code looking relatively tidy and understandable. I have also found that separating the two leaves less margin for PHP errors, if the HTML elements are separated from the PHP there is a smaller amount of PHP that can go wrong.
Ultimately I believe it is down to preference however I feel that separation has the following pros:
Tidier Code
Less of an Error Margin
Easy to Interpret
Easier to change HTML elements
Easier to changed Application Logic
Faster Loading (HTML is not going from Parser->Browser it goes straight to browser)
However some cons may be:
It only works in PHP5 (I Believe, could be wrong, correct if needed)
It may not be what one is used to
Untidy if done incorrectly (without indentation etc, however this is the same with anything)
But as you can see, the pros outweigh said cons. Try not to mix the two also, some separation and some intergration - this may get confusing for yourself and other developers that work with you.
I hope this helped.
Benefits of the first method (separating PHP and HTML):
You don't need to escape characters
It's also possible for code editors
to highlight/indent the markup.
It's arguably easier to read
There is no downside to this method,
compared to the second method.
Functionally: they both will work, so ultimately it is a preference.
Yet, you might consider that comments are a preference as well, your code would compile and run exactly the same without comments. However most people would agree comments are essential to writing and maintaining good code. I see this as being a similar subject matter. In the long run it will make it easier to read and maintain the code it if the two are separated.
So is it important? I would say Yes.
I kick off with: the first one you can open in a WYSIWYG editor, and still see some markup, which might makes it easier to maintain.
It says that what you put in echo '' it is first processed by the programming language and then sent to the browser, but if you directly put there html code without php, that code will load faster because there is no programming involved.
And the second reason as people above said is that you should have your 'large programming code' stored separately of the html code, and in the html code just put some calls to print results like 'echo $variable'. Or use a template engine like Smarty (like I do).
Best regards,
Alexandru.
Ouch!
All of the examples in your question are perfectly impossible to read. I'd say, you do yourself and those, who might read your code a great favour and use a template engine of sorts, say, Smarty. It is extremely easy to set up and use and it WILL separate your code from presentation. It doesn't require you to put everything in classes, it just makes sure, that your logic is in one file and presentation - in another one.
I don't know how in php but in asp.net separation has the following advantages.
1. separated code is easy to understand and develop
2. designer can work in html in the same time developer can write a code

Categories