php 用PHP编写TXT文件,想添加实际换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3857038/
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
Writing TXT File with PHP, Want to Add an Actual Line Break
提问by Chris
I am writing a TXT file using PHP. I want to insert actual line breaks into the TXT file wherever necessary. I have tried all combinations of \n \r \r\n \n\r ... but these are not causing any linebreaks to appear - in most cases, I am seeing the text "\n" appear in the TXT file, with no linebreak.
我正在使用 PHP 编写 TXT 文件。我想在必要的地方将实际的换行符插入到 TXT 文件中。我已经尝试了 \n \r \r\n \n\r 的所有组合......但这些都不会导致出现任何换行符 - 在大多数情况下,我看到文本“\n”出现在 TXT 文件中,没有换行符。
I have also tried chr(13).
我也试过 chr(13)。
Any other ideas would be appreciated.
任何其他想法将不胜感激。
回答by Matthieu Napoli
For "\n" to work, you need to use double quotes, not '\n'.
要使 "\n" 起作用,您需要使用双引号,而不是 '\n'。
Butyou should use the constant PHP_EOLinstead, so that it adapts automatically to the OS ("\n", "\r" or "\r\n").
但是您应该使用常量PHP_EOL,以便它自动适应操作系统(“\n”、“\r”或“\r\n”)。
file_put_contents('file.txt', 'Bla' . PHP_EOL . 'Bla');
回答by chigley
Sounds to me like you might be using single quotes, i.e. '\n'
rather than "\n"
.
在我看来,您可能正在使用单引号,即'\n'
而不是"\n"
.
If you wanted to continue with a single quotes bias (as you should!), two options:
如果您想继续使用单引号偏差(正如您应该的那样!),有两种选择:
file_put_contents('/path/to/file.txt', 'Hello friend!
This will appear on a new line.
As will this');
// or
file_put_contents('/path/to/file.txt', 'Hello friend!'."\n".'This will appear on a new line.'."\n".'As will this');
回答by user453756
\r\n in a windows server \n in linux Make sure you upload the file as ASCII.
\r\n 在 Windows 服务器中 \n 在 linux 确保您将文件上传为 ASCII。
回答by Colin
you could also use chr(10)
which is line break.
你也可以使用chr(10)
which 是换行符。
回答by álvaro González
You must write \n
in a double-quotedstring (in single-quoted strings no parsing takes place):
你必须写\n
在双引号的字符串(在单引号字符串没有解析发生):
"foo\r\nbar"
Further reference:
进一步参考: