Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

php - file_put_contents, file_append and line breaks

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

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

15812

If I add a line break like file_put_contents($filename, $commentnumber . " ", 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?

question from:https://stackoverflow.com/questions/3536564/file-put-contents-file-append-and-line-breaks

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

...tricky


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...