PHP Tag Removes Last Newline in Document

自作多情 提交于 2019-12-12 12:13:06

问题


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?


回答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.




回答2:


Try having it like to force the line break:

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

</div>



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


来源:https://stackoverflow.com/questions/11723835/php-tag-removes-last-newline-in-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!