php 将字符串数组写入由换行符分隔的文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11957021/
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 02:31:18  来源:igfitidea点击:

Writing a string array to text file separated by new line character

phphtml

提问by Klone

I have a PHP page which accepts input from user in a text area. Multiple strings are accepted as input from user & would contain '\n' and I am scanning it as:

我有一个 PHP 页面,它接受用户在文本区域中的输入。多个字符串被接受为来自用户的输入 & 将包含 '\n' 并且我将其扫描为:

$data = explode("\n", $_GET['TxtareaInput']);

Each string should be moved into the text file with new line character separation. This is the code I am using now and it separates each string with a '^M' character:

每个字符串都应移动到带有换行符分隔的文本文件中。这是我现在使用的代码,它用 '^M' 字符分隔每个字符串:

foreach($data as $value){
    fwrite($ourFileHandle, $value);
}

Is there anyway I can get each string followed by a carriage return?

无论如何我可以获得每个字符串后跟一个回车符?

采纳答案by raidenace

Try this:

尝试这个:

$data = explode("\n", $_GET['TxtareaInput']);
foreach($data as $value){
    fwrite($ourFileHandle, $value.PHP_EOL);
}

回答by madflow

You can simply write it back using implode:

您可以简单地使用内爆将其写回:

file_put_contents('file.csv', implode(PHP_EOL, $data));

回答by Jocelyn

If you want to add new lines, then why are you first removing them?

如果要添加新行,为什么要先删除它们?

$data = explode("\n", $_GET['TxtareaInput']);

Keep only this line:

只保留这一行:

fwrite($ourFileHandle, $data);

It will write your data to the file as it was received.

它将在收到您的数据时将其写入文件。

If you want to replace all new lines by carriage returns before writing to file, use this code:

如果要在写入文件之前通过回车替换所有新行,请使用以下代码:

    fwrite($ourFileHandle, str_replace("\n", "\r", $data));