Alex Rivera | Logout

file_put_contents, file_append and line breaks

Asked 2010-08-21T06:10:24.520
41

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 . "\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?

Edit
Report

3 Answers

74

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

answered 2010-08-21T06:21:56.483
20

pauls answer has the correct approach but he has a mistake. what you need ist the following:

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

the PHP_EOL constant makes sure to use the right line ending on mac, windows and unix systems the trim function removes any newline or whitespace on both sides of the string. converting to integer would be a huge mistake because 1. you might end up having zero, expecially because of white space or special characters (wherever they come from...) 2. ids dont necessarily need to be integers

answered 2010-08-22T16:58:43.657
1

annoyingregistration, what you have there is absolutely fine. PHP_EOL and "\n" are exactly the same.

The code you provided theres nothing wrong with it so it must be the value of $commentnumber that has a space at the end of it. as stated, run your $commentnumber through the trim() function.

file_put_contents($filename, trim($commentnumber . "\n"), FILE_APPEND);

Good luck.

answered 2010-08-21T08:42:25.563

Your Answer