file_put_contents, file_append and line breaks

user426965 picture user426965 · Aug 21, 2010 · Viewed 81.7k times · Source

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?

Answer

eridal picture eridal · Aug 21, 2010

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