Home » Php » php – file_put_contents and a new line help

php – file_put_contents and a new line help

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’ve got a file that I’m writing to and I cannot get file_put_contents to append the next entry on a new line, even after a newline character. What am I missing? I’m on a windows machine.

$file = 'test.txt';
$message = "test\n\n";
file_put_contents($file, $message, FILE_APPEND);
How to&Answers:

how are you viewing the contents of $file? if you’re using notepad you can’t see \n.

Answer:

try

$file = 'test.txt';
$message = "test".PHP_EOL;
file_put_contents($file, $message, FILE_APPEND);

or

$file = 'test.txt';
$message = "test\r\n";
file_put_contents($file, $message, FILE_APPEND);

Answer:

For the PHP_EOL you may not be seeing your new line because you are defining the end of the line after you write your new line. Therefore the new line is only made after the new content is added to the last line of your text file.

it should read like this:

$file = 'test.txt';
$message = 'some message that should appear on the last line of test.txt';
file_put_contents($file, PHP_EOL . $message, FILE_APPEND);

Answer:

For those who are passing the second argument to file_put_contents as an array rather than a string, it also works to put PHP_EOL as the last array element:

file_put_contents($file, array('value 1', 'value 2', PHP_EOL), FILE_APPEND);

Answer:

Just give a normal new line and it works

$file = 'test.txt';
$message = "test
";
file_put_contents($file, $message, FILE_APPEND);

Answer:

First, read something about the new line character. It is different for each operating system… There is LF, CR, CR+LF… Have a look here

On Windows, you need CR+LF (\r\n) as Mathieu already said.
On Linux, only LF is needed (\n)

But, to be sure, use PHP_EOL.

In using files, you would probably need to know more about path and directory separators. They are also different. Use DIRECTORY_SEPARATOR instead of forward-slash or back-slash 😉