Jake Z
Jake Z

Reputation: 1577

PHP Tag Removes Last Newline in Document

This issue is purely in the interest of having tidy HTML code output.

In a simple PHP file, you can choose when to have PHP embedded in the document by using the tags. However, it appears that when this tag is used directly above a regular HTML element, the newline separating the two is apparently removed or ignored.

Observe the following code in PHP

<div>
<?php echo "This is some extra text." ?>
</div>

The output is as follows

<div>
This is some extra text.</div>

However, if I add something directly after the tag,

<div>
<?php echo "This is some extra text." ?> Now the newline is honored.
</div>

it appears the newline is honored:

<div>
This is some extra text. Now the newline is honored.
</div>

Again, this is purely a cosmetic issue and has nothing to do with incorrectly rendering a page. I want the source code to be nice and readable, and certain I could add in the first echo the "\n" character at the end, but this does not feel satisfying and would also be rather annoying. Is there any remedy to this problem, or am I just doing something wrong?

Upvotes: 4

Views: 470

Answers (3)

L&#232;se majest&#233;
L&#232;se majest&#233;

Reputation: 8045

This is a long standing issue with PHP. Basically, if your close tag has a newline directly after it, PHP eats it. But if there's some other character immediately after the close tag (even a whitespace), then any linebreaks after it are respected.

E.g.

<?php echo "Hello"; ?>\nWorld

produces:

HelloWorld

And

<?php echo "Hello"; ?>\n\nWorld

produces:

Hello⏎
World

However,

<?php echo "Hello"; ?> \nWorld

produces

Hello ⏎
World

So the workaround is to either remember to add a newline at the end of the output of each block, or to insert a space between the close tag and the newline after it.

Upvotes: 3

Alex W
Alex W

Reputation: 38173

The \n character is invisible to you, but when you add the extra text after, you are hitting return/enter.

If you want the added text to have the newline character, just do the following:

<?php echo "This is some extra text.\n" ?>

Upvotes: 0

Biotox
Biotox

Reputation: 1601

Try having it like to force the line break:

<div>
<?php echo "This is some extra text." ?>

</div>

Upvotes: 0

Related Questions