PHP newline not working in text file

2019-03-17 09:16发布

问题:

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?

回答1:

$numberNewline = $number . "\n";
fwrite($file, $numberNewline);

Try this



回答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



回答3:

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



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



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


回答6:

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.



回答7:

$numberNewline = $number . '\r\n';

fwrite($file, $numberNewline);

Try This