php file_put_contents 和一个新行帮助

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2325241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:02:46  来源:igfitidea点击:

file_put_contents and a new line help

php

提问by jim

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_put_contents 将下一个条目附加到新行,即使在换行符之后也是如此。我错过了什么?我在 Windows 机器上。

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

采纳答案by bcosca

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

你是如何查看内容的$file?如果您使用的是记事本,则看不到\n.

回答by Mathieu

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

回答by Zambiki

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.

对于 PHP_EOL,您可能看不到新行,因为您在编写新行后定义了行尾。因此,仅在将新内容添加到文本文件的最后一行后才会创建新行。

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

回答by DJ Far

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 的人,它也可以将 PHP_EOL 作为最后一个数组元素:

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

回答by Rayiez

Just give a normal new line and it works

只需给一个正常的新行,它就可以工作

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

回答by user2602350

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

首先,阅读有关换行符的内容。每个操作系统都不一样...有LF, CR, CR+LF... 看看这里

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

在 Windows 上,正如 Mathieu 已经说过的那样,您需要CR+LF( \r\n) 。在 Linux 上,只需要LF( \n)

But, to be sure, use PHP_EOL.

但是,可以肯定的是,使用PHP_EOL.

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

在使用文件时,您可能需要了解更多关于路径和目录分隔符的信息。它们也不同。使用DIRECTORY_SEPARATOR而不是正斜杠或反斜杠;)