This question already has answers here:
How to properly indent PHP/HTML mixed code? [closed]
(6 answers)
Closed 9 years ago.
This has been bugging me today after checking the source out on a site. I use PHP output in my templates for dynamic content. The templates start out in html only, and are cleanly indented and formatted. The PHP content is then added in and indented to match the html formating.
<ul>
<li>nav1</li>
<li>nav2</li>
<li>nav3</li>
</ul>
Becomes:
<ul>
<?php foreach($navitems as $nav):?>
<li><?=$nav?></li>
<?php endforeach; ?>
</ul>
When output in html, the encapsulated PHP lines are dropped but the white space used to format them are left in and throws the view source formatting all out of whack. The site I mentioned is cleanly formatted on the view source output. Should I assume they are using some template engine? Also would there be any way to clean up the kind of templates I have? with out manually removing the whitespace and sacrificing readability on the dev side?
That's something that's bugging me, too. The best you can do is using tidy to postprocess the text. Add this line to the start of your page (and be prepared for output buffering havoc when you encounter your first PHP error with output buffering on):
ob_start('ob_tidyhandler');
You can't really get clean output from inlining PHP. I would strongly suggest using some kind of templating engine such as Smarty. Aside from the clean output, template engines have the advantage of maintaining some separation between your code and your design, increasing the maintainability and readability of complex websites.
i admit, i like clean, nicely indented html too. often it doesn't work out the way i want, because of the same reasons you're having. sometimes manual indentation and linebreaks are not preserverd, or it doesn't work because of subtemplates where you reset indentation.
and the machines really don't care. not about whitespace, not about comments, the only thing they might care about is minified stuff, so additional whitespace and comments are actually counter-productive. but it's so pretty *sigh*
sometimes, if firebugs not available, i just like it for debugging. because of that most of the time i have an option to activate html tidy manually for the current request. be careful: tidy automatically corrects certain errors (depending on the configuration options), so it may actually hide errors from you.
Does "pretty" HTML output matter? You'll be pasting the output HTML into an editor whenever you want to poke through it, and the editor will presumably have the option to format it correctly (or you need to switch editors!).
I find the suggestions to use an additional templating language (because that's exactly what PHP is) abhorrent. You'd slow down each and every page to correct the odd space or tab? If anything, I would go the other direction and lean towards running each page through a tool to remove the remaining whitespace.
The way I do it is:
<ul>
<?php foreach($navitems as $nav):?>
<li><?=$nav?></li>
<?php endforeach; ?>
</ul>
Basically all my conditionals and loop blocks are flush left within the views. If they are nested, I indent inside the PHP start tag, like so:
<ul>
<?php foreach($navitems as $nav):?>
<?php if($nav!== null) : ?>
<li><?=$nav?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
This way, I see the presentation logic clearly when I skim the code, and it makes for clean HTML output as well. The output inside the blocks are exactly where I put them.
A warning though, PHP eats newlines after the closing tag ?>. This becomes a problem when you do something like outputting inside a <pre> block.
<pre>
<?php foreach($vars as $var ) ?>
<?=$var?>
<?php endforeach; ?>
</pre>
This will output:
<pre>
0 1 2 3 4 5 </pre>
This is kind of a hack, but adding a space after the <?=$var?> makes it clean.
Sorry for the excessive code blocks, but this has been bugging me for a long time as well. Hope it helps, after about 7 months.
You few times I have tidied my output for debugging my generated HTML code I have used tabs and newlines... ie;
print "<table>\n";
print "\t<tr>\n";
print "\t\t<td>\n";
print "\t\t\tMy Content!\n";
print "\t\t</td>\n";
print "\t</tr>\n";
print "</table>\n";
I about fell over when I read "I'm really curious why you think it's important to have generated HTML that's "readable". Unfortunately, there were quite a few people on this page (and elsewhere) that think this way...that the browser reads it the same so why worry about the way the code looks.
First, keeping the "code" readable makes debugging (or working in it in general by you or a developer in the future) much easier in almost all cases.
Furthermore, AND MOST IMPORTANTLY, it's referred to as quality of workmanship. It's the difference between a Yugo and a Mercedes. Yes, they are both cars and they both will take you from point "A" to point "B". But, the difference is in the quality of the product with mostly what is not seen. There is nothing worse than jumping into a project and first having to clean up someone else's code just to be able to make sense of things, all because they figured that it still works the same and have no pride in what they do. Cleaner code will ALWAYS benefit you and anyone else that has to deal with it not to mention reflect a level of pride and expertise in what you do.
If it's REAL important in your specific case, you could do this...
<ul><?php foreach($navitems as $nav):?>
<li><?=$nav?></li><?php endforeach; ?>
</ul>
Although that is worse in my opinion, because your code is less readable, even though the HTML is as you desire.
I don't care how clean the output is - it's the original source code that produced it that has to be easy to parse - for me as a developer.
If I was examining the output, I'll run it through tidy to clean it up, if it were required to take a good look at it - but validators don't care about extra spaces or tabs either.
In fact, I'm more likely to strip whitespace out of the output HTML than put any in - less bytes on the wire = faster downloads. not by much, but sometimes it would help in a high traffic scenario (though of course, gzipping the output helps more).
Viewing unformatted source is very annoying with multiple nested divs and many records each containing these divs..
I came across this firefox addon called Phoenix Editor. You can view your source in it's editor and then click "format" and it works like a charm!
Link Here
Try xtemplate http://www.phpxtemplate.org/HomePage its not as well documented as id like, but ive used it to great effect
you would have something like this
<?php
$response = new xtemplate('template.htm');
foreach($navitems as $item)
{
$response->assign('stuff',$item);
$response->parse('main.thelist');
}
$response->parse('main');
$response.out('main');
?>
And the html file would contain
<! -- BEGIN: main -->
<html>
<head></head>
<body>
<ul>
<! -- BEGIN: thelist -->
<li>{stuff}</li>
<!-- END: thelist -->
</ul>
</body>
</html>
I Agree, A clean source is very important, Its well commented, well structured and maintence on those sources, scripts, or code is very quick and simple. You should look into fragmenting your main, using require (prior.php, header.php, title.php, content.php, post.php) in the corresponding places, then write a new function under prior.php that will parse and layout html tags using the explode method and a string splitter, have an integer for tab index, and whenever </ is in the functions string then integer-- whenever < and > but not /> and </ are in the string integer ++ and it all has to be placed properly.... , use a for loop to rebuild another string tabindex to tab the contents integer times.
Related
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.
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.
This question already has answers here:
How to properly indent PHP/HTML mixed code? [closed]
(6 answers)
Closed 9 years ago.
Here is a question that has been bugging me for a while, nowadays it's considered a good practice to indent HTML code but I've some reservations indenting code in a MVC pattern, here is a (silly) example:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Testing MVC Indentation</title>
</head>
<body>
<?php View('h1', 'I am a Level 1 Header'); ?>
<table>
<tr>
<td>
<?php View('h1', 'I am a Level 1 Header Inside a Table'); ?>
</td>
</tr>
</table>
</body>
</html>
To indent correctly, the first call to the h1 view (or partial) should return:
\t<h1>I am a Level 1 Header</h1>
While the second call to the h1 view should return:
\t\t\t\t<h1>I am a Level 1 Header Inside a Table</h1>
The h1 view however, has no idea of the indentation scope it's in, so how the hell can it return the data properly indented? Also, ignoring indentation in views can disclose part of the application logic (check the HTML source code of this page after <div id="content"> for a real-world example):
<body>
<h1>I am a Level 1 Header</h1>
<table>
<tr>
<td>
<h1>I am a Level 1 Header Inside a Table</h1>
</td>
</tr>
</table>
</body>
Not indenting at all solves all problems, but it also makes it harder to read and maintain:
<body>
<h1>I am a Level 1 Header</h1>
<table>
<tr>
<td>
<h1>I am a Level 1 Header Inside a Table</h1>
</td>
</tr>
</table>
</body>
The only feasible solution I see to this problem is by using Tidy and output buffering, but I wonder if it's worth the effort since it will make processing and loading unnecessarily (?) slow. Also, this will not make it easier the maintain the HTML code since it only indents the output, not the source.
I'm sorry for the "basic" question, but I've been focusing on business logic for the last years and I've been kinda disconnected with the presentation world - in the good old days my HTML code was all unindented, but then again I also used tables to design the layout - just trying to catch up now.
Any solutions / insights on this subject?
Related Questions:
Do you indent your HTML code?
Do you generate nicely formatted HTML?
How to properly indent PHP/HTML mixed code?
I would say, that there is a difference between HTML and Source Code Indentation. In a typical MVC View you use source code which I think should be indented in a readable fashion.
The actual HTML output though is a different thing. Of course chaoticly indented source looks kind of unprofessional (this is why I sometimes tend to just remove any indentation at all but that usually involves as you said some HTML post processing), but for the Browser itself if doesn't matter at all and if I really need to view the source I will use a formatter or Firebug which shows all DOM elements in a nicely formatted way.
As mentioned there is a difference between source code indentation and output indentation. The indentation of the source code can be different from the indentation of the output, because the output is constructed dynamically. When writing templates, the readability of the source code is most important. You should focus on that first! Usually the HTML indentation of the output is a non-issue.
Having said that, two practical approaches to get rid of indentation mismatch in your output:
Use a templating language that can properly indent the output
One example of the first is Haml, a templating language for Ruby. It takes a template like this:
%body
%h1 I am a Level 1 Header
%table
%tr
%td
%h1 I am a Level 1 Header Inside a Table
The output will be neatly formatted HTML similar to your example, all properly indented.
One obvious disadvantage of this approach is that you're not really writing HTML in your templates, you're writing in a different language with HTML-like semantics. This can be a problem, depending on who will maintain the views.
Strip all superfluous whitespace from the output, don't indent at all
Some template languages have options to remove all superfluous whitespace. Smarty for PHP has a whitespace trimming plugin that does this job nicely, for example. It completely works around the output beautification problem by purposely making all output equally non-indented. It also saves a very marginal amount of bandwidth.
A PHP-only solution would be to use ob_start() with its $output_callback handler (which is documented here). You can write a simple callback that strips the excessive whitespace, similar to the Smarty plugin. Contrary to using Tidy in the output callback, this will still allow you to flush the buffer before the end of the page to speed up long/slow pages.
Sorry for adding a third answer! It's a been a while, and I'd rather add an answer, please don't down-vote me for that. I just think this should be said here:
This seems to work, aka having 2 different "threads" of indentation, one for PHP and one for HTML:
<table>
<?foreach($list->sections as $sKey => $section) { ?>
<tr><td><h4><?= $section->label ?></h4></td></tr>
<? foreach($section->items as $iKey => $item) { ?>
<tr><td><?= $item->label ?></td></tr>
<? } ?>
<?} ?>
</table>
By always having the php tag start at the beginning of the line, and indent inside the php block code, the resulting code stays clean:
<table>
<tr><td><h4>Books 1</h4></td></tr>
<tr><td>Some Book</td></tr>
<tr><td>Some Other Book</td></tr>
<tr><td><h4>Books 2</h4></td></tr>
<tr><td>Some Book in List 2</td></tr>
</table>
And the indentantion logic of the PHP and of the HTML are kept in the source file, albeit each on it's own.
I think something can be invented here to keep track of indenting.
It is possible, I believe, to have properly indented PHP and properly indented HTML at the same time, but code needs to be written to handle that, either as a PHP extension or a library (which is much less elegant and efficient).
My first guess would be for PHP to keep track of the indentation of the HTML, and when a new line is printed, resume at the previous level of indentation, sort of what most IDE's do when you type enter.
The PHP programmer can be given control over this with the functions like these (I'm just making this stuff up right now):
tab($n) : move the indentation level $n tabs to the right (add $n tabs)
detab($n) : remove $n tabs from the level of indentation
stop() : stops indentation. no tabs will be added to output. this is useful for HTML PRE tags.
resume() : resume indentation at the previous level after a stop().
What I sometimes do is use \t in double-quoted strings for some basic indentation of HTML. It helps me debug stuff. Also, I keep the HTML inside templates as much as possible, even if it means riddling my templates with foreach loops. In the template (known as "view" in MVC), the PHP code indentation usually follows the HTML code.
I might also add an argument to functions that generate HTML, to make them "indent aware" example:
buildSomeHtmlList($data, $indent=0)
That results into mostly indented HTML, and that suits me.
BTW, in your example, this is not what is supposed to happen, AFAIk, the H1 inside the table should be properly indented, normally, since the PHP output starts at "<?", at which point the tabs have already been printed.
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.
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.)