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

匿名 (未验证) 提交于 2019-12-03 02:23:02

问题:

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:

$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:

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

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

回答1:

Try this:

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


回答2:

You can simply write it back using implode:

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


回答3:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!