php标签之前/之后的空格

I have one small issue with my code below, I'd like the HTML view of the source code to be "tidy" as well as the PHP, I've spent days searching but I've drawn a blank as to why the HTML side is not tidy, the only thing I'm guessing is extra whitespace is being generated, if that's the case I'm not sure why, if anyone could help it would be appreciated, thanks.

html

<div class='col-md-12'>
        <div class='alert alert- info'>
        Already Logged In
    </div>
    </div>

php

<div class='col-md-12'>
    <?php if ($action=='logged-in'): ?>
    <div class='alert alert- info'>
        Already Logged In
    </div>
    <?php endif ?>
</div>

Your lines with just PHP code still keep their whitespace, so the spaces at the beginning of that line and the at the end still count.

Unfortunately, this means you'd have to have your code look like this:

<div class='col-md-12'>
<?php if ($action=='logged-in'): ?>    <div class='alert alert- info'>
        Already Logged In
    </div>
<?php endif ?></div>

Pretty ugly, right?

You have a couple options:

  • Run the final HTML (captured using an output buffer) through something like Tidy, which has indentation correction built-in as an option. A lot of work for something no one's ever gonna see, but it'll do the trick.
  • Use a templating system to separate out the PHP a bit. Something like Twig can probably be massaged a little easier into the nicely indented HTML you want, but there'll still be some of the same troubles if you're not careful.
  • Stop caring. (This is my recommendation.) Focus on the readability and simplicity of the code you'll actually be working with, not the whitespace of the resulting HTML, which pretty much no one will ever notice or care about. Take a look at the HTML generated for any major website - Amazon.com, Facebook.com, Google.com, etc. - and you'll see that this is the standard practice.

Since it looks like the root <div> will be there no matter what, try using the following:

echo
'<div class="col-md-12">',
    ($action == 'logged-in' ? '
    <div class="alert alert-info">
        Already Logged In
    </div>' : '
    '), '
</div>';

Fiddle: Live Demo