In PHP I am trying to create a newline character:
echo $clientid;
echo ' ';
echo $lastname;
echo ' ';
echo '\r\n';
Afterwards I open the created file in Notepad and it writes the newline literally:
1 John Doe\r\n 1 John Doe\r\n 1 John Doe\r\n
I have tried many variations of the \r\n
, but none work. Why isn't the newline turning into a newline?
For any echo statements, I always use
<br>
inside double quotes.For some reason, every single post asking about newline escapes in PHP fails to mention the case that simply inserting a newline into single-quoted strings will do exactly what you think:
ex 1.
Example 1 clearly does not print the desired result, however, while it is true you cannot escape a newline in single-quotes, you can have one:
ex 2.
Example 2 has exactly the desired behavior. Unfortunately the newline that is inserted is operating system dependent. This usually isn't a problem, as web browsers/servers will correctly interpret the newline whether it is \r, \r\n, or \n.
Obviously this solution is not ideal if you plan to distribute the file through other means then a web browser and to multiple operating systems. In that case you should see one of the other answers.
note: using a feature rich text editor you should be able to insert a newline as a binary character(s) that represents a newline on a different operating system than the one editing the file. If all else fails, simply using a hex editor to insert the binary ascii character would do.
I have also tried this combination within both the single quotes and double quotes. But none has worked. Instead of using
\n
better use<br/>
in the double quotes. Like this..Actually
\r\n
is for the html side of the output. With those chars you can just create a newline in the html code to make it more readable:will output:
that viewing the page will be:
If you really meant this you have just to fix the single quote with the "" quote:
Otherwise if you mean to split the text, in our sample 'First line' and 'Second line' you have to use the html code:
<br />
:that will output:
Also it would be more readable if you replace the entire script with:
For platform independent line ending you can use the predefined
PHP_EOL
constant, as in:Use the constant PHP_EOL to get the right character no matter the platform.
http://us3.php.net/manual/en/reserved.constants.php
A simple usage example: