在 PHP 中向文件写入新行(换行)

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

Writing a new line to file in PHP (line feed)

phpnewlinefopenfwritelinefeed

提问by VIVA LA NWO

My code:

我的代码:

$i = 0;
$file = fopen('ids.txt', 'w');
foreach ($gemList as $gem)
{
    fwrite($file, $gem->getAttribute('id') . '\n');
    $gemIDs[$i] = $gem->getAttribute('id');
    $i++;
}
fclose($file);

For some reason, it's writing \nas a string, so the file looks like this:

出于某种原因,它写成\n一个字符串,所以文件看起来像这样:

40119\n40122\n40120\n42155\n36925\n45881\n42145\n45880

From Google'ing it tells me to use \r\n, but \ris a carriage return which doesn't seem to be what I want to do. I just want the file to look like this:

从谷歌它告诉我使用\r\n, 但它\r是一个回车,这似乎不是我想要做的。我只希望文件看起来像这样:

40119
40122
40120
42155
36925
45881
42145
45880

Thanks.

谢谢。

回答by Artefacto

Replace '\n'with "\n". The escape sequence is not recognized when you use '.

替换'\n'"\n"。使用时无法识别转义序列'

See the manual.

请参阅手册

For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopenshould get "wb", not "w").

关于如何写行尾的问题,请看这里的注释。基本上,不同的操作系统对行尾有不同的约定。Windows 使用“\r\n”,基于 unix 的操作系统使用“\n”。你应该坚持一个约定(我选择了“\n”)并以二进制模式打开你的文件(fopen应该得到“wb”,而不是“w”)。

回答by Aldarien

Use PHP_EOLwhich outputs \r\nor \ndepending on the OS.

使用PHP_EOL哪些输出\r\n\n取决于操作系统。

回答by user1649798

PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manualposting:

自 PHP 4.3.10 和 PHP 5.0.2 起,PHP_EOL 是 PHP 中的预定义常量。看手动贴:

Using this will save you extra coding on cross platform developments.

使用它可以为您节省跨平台开发的额外编码。

IE.

IE。

$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);

If you looped through this twice you would see in 'somefile':

如果你循环两次,你会在“somefile”中看到:

some data
some data

回答by Alix Axel

You can also use file_put_contents():

您还可以使用file_put_contents()

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);