PHP tag deletes last line in document

This problem is solely in having accurate HTML output.

In a simple PHP file, you can choose when PHP is embedded in the document using tags. However, it seems that when this tag is used directly above a regular HTML element, the new line separating the two appears to be deleted 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 seems that the new line is being followed:

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

Again, this is a purely cosmetic problem and has nothing to do with incorrect page display. I want the source code to be pleasant and readable, and I could add the "\ n" character at the end of the first echo, but this does not seem satisfactory, and it will also be quite unpleasant. Is there any way to solve this problem, or am I just doing something wrong?

+4
source share
3 answers

This is a longstanding issue with PHP. Basically, if your close tag has a new line immediately after it, PHP eats it. But if there is some other character immediately after the close tag (even a space), then any lines after it will be respected.

eg.

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

gives:

 HelloWorld 

and

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

gives:

 Hello⏎ World 

However

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

produces

 Hello ⏎ World 

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

+3
source

Try to force a line break:

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

The \n character is invisible to you, but after adding additional text, you press return / enter.

If you want the added text to have a newline, follow these steps:

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

All Articles