PHP newline not working in text file
Solution 1
$numberNewline = $number . "\n";
fwrite($file, $numberNewline);
Try this
Solution 2
'\n'
in single quotes is a literal \n
.
"\n"
in double quotes is interpreted as a line break.
http://php.net/manual/en/language.types.string.php
Solution 3
If inserting "\n" does not yield any results, you can also try "\r\n" which adds a "carriage-return" and "new line."
Solution 4
Use PHP_EOL. PHP_EOL is platform-independent and good approach.
$numberNewline = $number .PHP_EOL;
fwrite($file, $numberNewline);
PHP_EOL is cross-platform-compatible(DOS/Mac/Unix).
Solution 5
The reason why you are not seeing a new line is because .txt files write its data like a stack. It starts writing from the beginning, then after it finishes, the blinking line (the one indicating where your next character is going to go) goes back to the beginning. So, your "\n" has to go in the beginning.
Instead of writing:
<?php
$sampleLine = $variable . "\n";
$fwrite($file, $sampleLine);
?>
You should write:
<?php
$sampleLine = "\n" . $variable;
$fwrite($file, $sampleLine);
?>
JJJollyjim
Updated on January 28, 2021Comments
-
JJJollyjim over 3 years
I am using the PHP code:
$numberNewline = $number . '\n'; fwrite($file, $numberNewline);
to write $number to a file.
For some reason \n appears in the file. I am on a mac. What might be the problem?