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>
我的代码下面有一个小问题,我希望源代码的HTML视图是“ 整洁“以及PHP,我花了几天时间搜索,但我已经画了一个空白,为什么HTML方面不整洁,我猜的唯一的事情是生成额外的空格,如果是这样的话我 我不知道为什么,如果有人能提供帮助,将不胜感激,谢谢。 p>
html p>
&lt; div class ='col -md-12'&gt;
&lt; div class ='alert alert-info'&gt;
已登录
&lt; / div&gt;
&lt; / div&gt;
code> pre >
php p>
&lt; div class ='col-md-12'&gt;
&lt;?php if($ action ==' 已登录'):?&gt;
&lt; div class ='alert alert-info'&gt;
已登录
&lt; / div&gt;
&lt;?php endif?&gt;
&lt; / div&gt;
code> pre>
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