Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 932
user426965 Avatar asked Aug 21 '10 06:08

user426965


1 Answers

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

like image 56
2 revs Avatar answered Oct 07 '22 15:10

2 revs