Reputation: 403
This one is bothering me for a while. Let's say we have a simple PHP-File:
Line 0
Line 1
<?="Line 2"?>
Line 3
Processing this file will result in:
Line 0
Line 1
Line 2Line 3
Where did the line feed after ?>
go? The linefeed is not beeing devoured when placing some character after the closing tag (e.g. ?>.
).
Is there a way to control this behaviour? I'm not willing to place whitespaces after the closing tag, because my IDE is configured to remove whitespaces before linefeeds (and I like it that way).
Upvotes: 6
Views: 143
Reputation: 437336
This is actually a feature (believe it or not). PHP consumes a linefeed if it directly follows a PHP close tag:
The closing tag for the block will include the immediately trailing newline if one is present.
This was clearly put in so that a PHP file ending with a blank line would not cause a newline to occur in the output when include
d from another script. So it's really a "protect the ignorant" feature from the old days that we have to live with for the foreseeable future.
If you really want the newline there are other options: from simply putting in two newlines after the closing tag (the second will work!) to echoing a newline from code.
Upvotes: 4
Reputation: 522024
Yes, indeed:
The closing tag for the block will include the immediately trailing newline if one is present.
http://php.net/manual/en/language.basic-syntax.instruction-separation.php
Meaning, if the ?>
is the last thing on the line, the newline will be removed as part of the closing PHP block. You need to explicitly echo
a newline or add an additional newline.
Upvotes: 5
Reputation: 173552
Outside of the <?php
and ?>
tags, the PHP interpreter operates in HTML mode and spacing inside HTML mode is less of an issue than it is for text contents.
To generate text with PHP you should use plain strings and build your output in this fashion:
$var = "Line 2";
$s = "Line 0\nLine 1\n$var\nLine3";
At least this won't give you a nasty, though documented, surprise :)
Upvotes: 1