Why New Line (“\n”) in PHP is Not Working September 15, 2012Posted by Tournas Dimitrios in PHP.
One thing that took me a long time until I could give an explanation was the new line tag (\n) in PHP-scripts . I copied PHP-script examples from books and other documentation , the “\n” line feed tag was ignored by my browser . Lines of text that supposed to be displayed on separate lines , were just concatenated into the same line . If text (with “\n” tags) were stored into a text-file and that file was opened directly into the browser then each text-line was displayed as it should (on separate lines) . To circumvent this “unknown-bug” I had to replace all “\n” strings by an “< b r /> ” tag . But then , when I opened these files in my browser , “br” tags where not translated as new-lines (just “br” was displayed on the screen) . I couldn’t give a theoretical explanation for this “browser-behavior” and arbitrary designated it as a “unknown-bug” 🙂 . As time moved on , I learned “step-by-step” new PHP concepts , until one day , I discovered the hidden development tool that each browser has embedded . This tool helps us to shed light into actions that occur behind the scenes during web-communications . Actually the browser displays the result of different actions (no matter which , Ajax – JQuery – CSS) . And besides all these actions , browser behaviour is customisable by header-fields . Wikipedia has a long list of these header fields , but the most important field (in focus of this article) , is the Content-Type field .
PHP outputs to a browser (usually) , which renders the output as HTML by default . In HTML , a newline tag (\n) is treated as white-space . Using header(‘Content-type: text/plain’); will cause the output to be rendered as plain text (the “\n” will render text on separate lines ) . Remember that header() must be called before any actual output is sent , either by normal HTML tags, blank lines in a file, or from PHP. A simple code could be as follows :
<?php header('Content-type: text/plain') ; $string = "Line 1\nLine 2" ; echo $string ;
Hope this article has helped some [new]developers not to designate the “\n” tag as “unknown-bug” (as I did in the past 🙂 ) .