file_put_contents,file_append和换行符 [英] file_put_contents, file_append and line breaks

查看:146
本文介绍了file_put_contents,file_append和换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个PHP脚本,该脚本将数字添加到文本文件中.我想在每一行上都有一个数字,就像这样:

I'm writing a PHP script that adds numbers into a text file. I want to have one number on every line, like this:

1
5
8
12

如果我使用file_put_contents($filename, $commentnumber, FILE_APPEND),则结果如下:

If I use file_put_contents($filename, $commentnumber, FILE_APPEND), the result looks like:

15812

如果我添加一个像file_put_contents($filename, $commentnumber . "\n", FILE_APPEND)这样的换行符,则会在每个数字之后添加空格,并在末尾添加一个空行(下划线表示空格):

If I add a line break like file_put_contents($filename, $commentnumber . "\n", FILE_APPEND), spaces are added after each number and one empty line at the end (underscore represents spaces):

1_
5_
8_
12_
_
_

如何获取该函数以所需的方式添加数字,而不能使用空格?

How do I get that function to add the numbers the way I want, without spaces?

推荐答案

您是否尝试过使用PHP EOL常量?

Did you tried with PHP EOL constant?


file_put_contents($filename, $commentnumber . PHP_EOL, FILE_APPEND)

-添加了---

--- Added ---

我只是意识到我的文件编辑器做了同样的事情,但不要担心,它只是一个鬼字符,编辑器放置在其中以表示存在换行符 你可以试试这个

I just realize that my file editor does the same, but don't worrie, is just a ghost character that the editor places there to signal that there is a newline You could try this


A file with EOL after the last number looks like:
1_
2_
3_
EOF

but a file without that last character looks like

1_
2_
3
EOF

where _ means a space character

您可以尝试使用php解析文件内容,以查看其中的内容

You could try to parse the file contents using php to see what's inside


$lines = explode( PHP_EOL, file_get_contents($file));
foreach($lines as $line ) {
    var_dump($line);
}

...棘手

这篇关于file_put_contents,file_append和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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