开发者

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


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


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


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


Just give a normal new line and it works

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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜