'Is there a way to force a new line after php closing tag ?> when embedded among html?
I have been searching online with little success for a way to force php to output a newline after a closing php tag ?> so that my HTML will be rendered as I see it before its parsed by PHP so that it will look neat and tidy when viewing the html source code for a page.
I want to stop it from removing the newline and causing the next line from wrapping up and therefore ruining the format of the page. Is there a specific php.ini setting I can change to disable this behaviour?
All my code logic files have ?> removed from the end of them so I wont need to worry about them injecting extra newlines which is why I believe PHP was coded to strip the trailing new lines.
Solution 1:[1]
This is an old question, but to keep the new line, simply place a space after the closing tag.
Source: http://php.net/manual/en/language.basic-syntax.instruction-separation.php
Solution 2:[2]
There is no way to change this behavior. To make it clear what's happening, I always explicitly put the newline character in my template files.
Hello,
Foo: <?php echo $foo."\n"; ?>
Bar: <?php echo $foo."\n"; ?>
This concludes foo and bar.
Outputs:
Hello,
Foo: foo
Bar: bar
This concludes foo and bar.
Solution 3:[3]
You can try this:
echo "output \n";
or even this much less elegant technique:
echo "output
";
Please paste some example code snippet to get more specific help.
Solution 4:[4]
You can't always just start a block level element after the php tag.
Sometimes, you are generating plain text for inside a textarea.
Other times, you are not generating HTML strings at all.
- SQL statement
- email body
- other non-HTML strings
Solution 5:[5]
My compulsive habits drive me to similar goals. Sadly, there is no elegant solution for this. Two suggestions:
Output a newline character where you want to break the HTML code like so:
echo 'Hello World'.chr(10);PHP's 'echo' command is not an actual function so you cannot override it; however, you could create a wrapper and use that instead:
function myecho($string, $newline=true) { echo $string; if($newline) echo chr(10); }
Neither solution is elegant, but then again, neither is the HTML output if you don't add line breaks.
Solution 6:[6]
You can make this slightly more elegant:
<?=$var.PHP_EOL?>
But in the end this is just a missing feature: If you're not in HTML/XML-context, just want to output simple, pure text you WANT to output the text "as is" and not have magically stripped the newlines away.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | atw527 |
| Solution 2 | marcovtwout |
| Solution 3 | erenon |
| Solution 4 | Alex |
| Solution 5 | Jonesy |
| Solution 6 | ssilk |
