Home » Php » PHP newline not working in text file

PHP newline not working in text file

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:
$numberNewline = $number . "\n";
fwrite($file, $numberNewline);

Try this

Answer:

'\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

Answer:

If inserting “\n” does not yield any results, you can also try “\r\n” which adds a “carriage-return” and “new line.”

Answer:

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).

Answer:

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);
?>

Answer:

None of the above worked for me but it was so simple – here is the code…
please use the KISS method.

echo file_put_contents("test.txt","\r\n \r\n$name \r\n$email \r\n$phone", FILE_APPEND);

It set a new blank line and then appends one line at a time.

Answer:

$numberNewline = $number . ‘\r\n’;

fwrite($file, $numberNewline);

Try This