用PHP编写新行文件 [英] Writing a new line to file in PHP

查看:101
本文介绍了用PHP编写新行文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

$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 \n as a string, so the file looks like this:

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

从Google告诉我使用 \r\\\
,但 \r 是一个回车,似乎不是我想要做的。我只是想要这样的文件:

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

40119
40122
40120
42155
36925
45881
42145
45880

谢谢

推荐答案

'\\\
'
替换为 \\\
。当您使用'时,转义序列无法识别。

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

请参阅手动

有关如何写行尾的问题,请参阅请注意此处。基本上,不同的操作系统对于线路结束有不同的约定。 Windows使用\\\\,基于unix的操作系统使用\\\
。你应该坚持一个惯例(我选择了\\\
),并以二进制模式打开你的文件( fopen 应该得到wb而不是w) 。

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 (fopen should get "wb", not "w").

这篇关于用PHP编写新行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆