views:

157

answers:

8

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>
+6  A: 

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.

Ólafur Waage
It's either <? php echo $this->foo ?> or <?=$this->foo?>. What you have is redundant.
ryeguy
Actually <?= is supposed to be deprecated. But we all know how long deprecated features in PHP stay around.
Brandon Hansen
+2  A: 

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).

Brandon Hansen
A: 

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.

Greg Mattes
Why the downvote? The OP states that "it bothers me", not that it is a problem to visitors, so this is a perfectly valid solution to his question, even if it just solves it for him.
Jergason
I didnt downvote, but this won't help formatting your webpage after PHP scripts execute.. All it'll help you do is create a static html page that was formatted with firebug.
Daniel
A: 

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 ?> )

dnagirl
A: 

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.

Alan Storm
+1  A: 

Just so you know, <?= actually means <?php echo. So you only have to do <?=$username?>

ryeguy
A: 

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])

JimR
A: 

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.)

bobince