PHP - how to create a newline character?
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?
Only double quoted strings interpret the escape sequences
\n as '0x0D' and '0x0A' respectively, so you want:
Single quoted strings, on the other hand, only know the escape sequences
So unless you concatenate the single quoted string with a line break generated elsewhere (e. g., using double quoted string
"\r\n" or using
chr(0x0D).chr(0x0A)), the only other way to have a line break within a single quoted string is to literally type it with your editor:
$s = 'some text before the line break some text after';
Make sure to check your editor for its line break settings if you require some specific character sequence (
\r\n for example).
Read more… Read less…
The "echo" command in PHP sends the output to the browser as raw html so even if in double quotes the browser will not parse it into two lines because a newline character in HTML means nothing. That's why you need to either use:
echo [output text]."<br>";
when using "echo", or instead use fwrite...
This will output HTML newline in place of "\n".
Use the constant PHP_EOL to get the right character no matter the platform.
A simple usage example:
<?php $data = 'First line' . PHP_EOL . 'Second line' . PHP_EOL . 'Third line'; file_put_contents("filename.txt", $data); ?>
Strings between double quotes
"" interpolate, meaning they convert escaped characters to printable characters.
Strings between single quotes
'' are literal, meaning they are treated exactly as the characters are typed in.
You can have both on the same line:
echo '$clientid $lastname ' . "\r\n"; echo "$clientid $lastname \r\n";
$clientid $lastname 1 John Doe
\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:
echo "<html>First line \r\n Second line</html>";
<html>First line Second line</html>
that viewing the page will be:
First line Second line
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:
First line<br />Second line
that will output:
First line Second line
Also it would be more readable if you replace the entire script with:
echo "$clientid $lastname \r\n";