PHP标记删除文档中的最后一个换行符 [英] PHP Tag Removes Last Newline in Document
问题描述
在一个简单的PHP文件中,您可以选择何时将PHP嵌入到文档中使用标签。然而,看起来,当这个标签直接用在常规的HTML元素上方时,分隔这两个元素的换行显然会被删除或忽略。
观察下面的PHP代码
< div>
<?php echo这是一些额外的文本。 ?>
< / div>
输出如下
< DIV>
这是一些额外的文字。< / div>
然而,如果我在标签之后直接添加了一些东西,
< div>
<?php echo这是一些额外的文本。 ?>现在换行符很荣幸。
< / div>
看起来换行符很好:
< DIV>
这是一些额外的文字。现在换行符很荣幸。
< / div>
同样,这纯粹是一个整容问题,与正确渲染页面无关。我希望源代码更好,更易读,并且我可以在第一个回声中添加最后的\ n字符,但这并不令人满意,而且也很烦人。是否有任何补救措施,或者我只是做错了什么?
基本上,如果你的关闭标签在它后面有一个换行符,PHP就会吃掉它。但是如果在关闭标记(即使是空格)之后立即有其他字符,那么在它受到尊重后任何换行符。例如
<?php echoHello; ?> \\\
World
产生:
HelloWorld
和
<?php echoHello; ?> \\\
\\\
World
产生:
您好
全球
不过,
<?php echoHello; ?> \\\
World
产生
您好⏎
全球
所以解决方法是记住在每个块的输出结尾添加一个换行符,或者在结束标签和后面的换行符之间插入一个空格。
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?
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.
这篇关于PHP标记删除文档中的最后一个换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!