How to Properly Indent PHP/Html Mixed Code

How to properly indent PHP/HTML mixed code?

The PHP and the HTML should each be indented so that they are correct with respect to themselves in source form, irrespective of each other and of outputted form:

<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table>

How to properly indent PHP with echoes

My opinion is that PHP being primarily a templating system, you shouldn't print HTML directly with it, only values. So I go for the second way.

I agree that writing <?php echo $variable; ?> is quitte messy (and ugly when there is many of them), but you can use the PHP short echo tags1, like this : <?= $variable ?>, which look way better and don't bloat your view. It is in fact exactly what templating systems built on PHP do, only without wrapping (and you get syntax highlighting as a bonus).

As a rule of thumb, avoid concatenation and evaluation of strings, that's a bad habit to take from a performance point of view, and not readible in the long term.

1 PHP short echo tags aren't discouraged anymore, because since PHP 5.4 they can't be turned off anymore, thus avoiding compatibility issues. On the other hand, PHP short open tag still are (unless I'm mistaken), so don't use them.

PhpStorm: How to separate PHP & HTML indentation

No, not currently possible. See this comment

How do you indent your HTML?

Amazing question.

9 answers and 3 comments so far, and looks like nobody bothered to read the question body, but just repeated some gospel triggered by a keyword in the title - a most preferred manner to answer questions on the blessed site of stackoverflow.

Yet the question not that simple/one-layered.

I have to admit, it's ambiguous itself. So, we have to dig it out.

1) How do you indent your HTML?

Use templates, dude. Use templates. The only answer.

2) Is there any solution for the function to somehow know how many \t 's or spaces to add, or somehow automatically indent the html?

Of course there isn't.

PHP knows nothing of HTML, indents and such.

Especially when no HTML is ready yet(!)

3) If I add another container DIV, this doesn't produce correctly indented code.

The key question of the question.

The question for sake of which the question were asked.

Yet hardest of them all.

And the answer is kind of ones I showed total disagreement with, hehe:

Although relative order of tags is important, for the resulting large HTML it is possible to move some blocks out of row:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello</h1>
<div>
<!-- news list -->
<div>
<ul>
<li>1..</li>
<li>2..</li>
<li>3..</li>
<li>4..</li>
</ul>
</div>
<!-- /news list -->
</div>
<div>
<!-- pagination -->
<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
<li>Black</li>
</ul>
<!-- /pagination -->
</div>
</body>
</html>

It will let you have proper indention in the meaningful blocks, yet keep the main HTML in order.

As a side effect it will keep your lines on the screen :)

To keep good indentation inside sub-templates, I'd strongly suggest using PHP-based templates. Not ugly HEREDOC for goodness' sake!

Here is only one rule to follow with PHP templates:

always keep PHP blocks to the left side. That's all.

To keep indentation between PHP nested blocks, just indent them inside <? ?>

Example:

<ul>
<? foreach ($thelist as $color): ?>
<li>
<? if ($color == $current): ?>
<b><?=$color?></b>
<? else ?>
<a href="?color=<?=$color?>"><?=$color?></a>
<? endif ?>
</li>
<? endforeach ?>
</ul>

This will produce correctly indented HTML, while keeping order of both HTML and PHP in the template, making developer's life easer both at development and debugging.

Do not listen to anyone who says "no need to indent your code at all!". They are merely hobbyists, not the real developers. Anyone who have an idea of what debugging is, who had hard times debugging their code, would tell you that proper indentation is essential.

Format code command for PHP/HTML in Visual Studio Code

Update 2021-07-21

It's been more than half a decade since I first wrote this answer. The extensions to which I originally linked are abandoned, and Visual Studio Code's intrinsic PHP support hasn't improved, which is disappointing. The only decent extension still standing of which I'm aware is PHP Intelephense, which uses a freemium model: basic features are free, and a lifetime license is $12 USD as of writing.

The free version of Intelephense supports code formatting with the usual shortcuts (Alt + Shift + F on Windows and Linux, ⌥⇧F on macOS). Visual Studio Code continues to lack built-in support for PHP code formatting and will direct you to the extension marketplace if you attempt to format PHP without an appropriate extension installed.

Original answer

Visual Studio Code has pretty awesome PHP support. What it lacks is covered by extensions. A quick search reveals at least three (1, 2, and 3) that claim to support PHP formatting.

They mostly seem to use the standard shortcut of Alt + Shift + F on Windows/Linux, with varying shortcuts on Mac. If you're on Mac, give ⌥⇧F a try.

HTML Indentation in the mVc World

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.

Correct indentation of HTML and PHP using Vim

This still bothers me. I only just decided that the best work-around (for me personally) is this:

:set filetype=html

And then highlight your text and hit =. BOOM! HTML formatting succes. (Not ideal, I know, but at least it works.)

Can I configure PHP to automatically format the HTML it generates?

You could do this (my preference):

<html>
<body>
<h1>Header One</h1>
<p>Hello World!</p>
<?php echo '<p>Hello Hello!</p>'; ?>
</body>
</html>

Or:

<?php

$html = '<html><body><h1>Header One</h1><p>Hello World!</p></body></html>';

$tidy = new tidy();
$tidy->parseString($html, array('indent'=> true,'output-xhtml'=> true), 'utf8');
$tidy->cleanRepair();

echo $tidy;

?>";

...would print:

<html>
<body>
<h1>Header One</h1>
<p>Hello World!</p>
</body>
</html>


Related Topics



Leave a reply



Submit