Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Solution 2:

Try having it like to force the line break:

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

</div>

Solution 3:

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

Post a Comment for "PHP Tag Removes Last Newline In Document"