51

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);
jim
  • 513
  • 1
  • 4
  • 4

6 Answers6

118

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);
Mathieu
  • 5,495
  • 2
  • 31
  • 48
  • 1
    @Gordon -1 for using `PHP_EOL`! This constant is only useful if you use a file for internal purposes and is massively overused. In most cases, UNIX-friendly `\n` is a better choice. – Robo Robok May 28 '18 at 20:26
  • 6
    @RoboRobok question was about `\n` not working on a windows machine, `PHP_EOL` or `\r\n` seems very appropriate here. this is not about "most cases" – Mathieu Jun 27 '18 at 17:47
32

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);
Zambiki
  • 321
  • 3
  • 2
15

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

Alfred
  • 21,058
  • 61
  • 167
  • 249
bcosca
  • 17,371
  • 5
  • 40
  • 51
5

Just give a normal new line and it works

$file = 'test.txt';
$message = "test
";
file_put_contents($file, $message, FILE_APPEND);
Rayiez
  • 1,420
  • 19
  • 20
4

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);
DJ Far
  • 497
  • 5
  • 12
2

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

AP.
  • 8,082
  • 2
  • 24
  • 33