• 8
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 187

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 187
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

file_put_contents and a new line help

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

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);
  • 96
Reply Report
      • 2
    • @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 is a better choice.
      • 1
    • @RoboRobok question was about not working on a windows machine, PHP_EOL or seems very appropriate here. this is not about "most cases"

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);
  • 23
Reply Report

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

  • 12
Reply Report

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);
  • 3
Reply Report

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

  • 1
Reply Report