PHP file_put_contents newline problem

I cannot write an array to a text file in new lines. My code is:

echo '<pre>'; print_r($final_result); echo '</pre>'; 

Exit

 Array ( [0] => Something1 [1] => Something2 [2] => Something3 ) 

Then

 file_put_contents($file, trim($final_result . "\n"), FILE_APPEND); 

Exit

 Something1Something2Something3Array 

My goal :

 Something1 Something2 Something3 

Any ideas? :)

+7
php
source share
4 answers

What about

 file_put_contents($file, implode(PHP_EOL, $final_result), FILE_APPEND); 
+14
source share

Different platforms use different newlines. To make this happen, php provides a built-in constant that takes care of all of them: PHP_EOL

+2
source share

Your array should be such as to insert a new row after each value

 Array ( [0] => Something1\n [1] => Something2\n [2] => Something3\n ) 

Performing this action:

 file_put_contents($file, trim($final_result . "\n"), FILE_APPEND); 

You insert a new line after the full array

As @NielsKeurentjes said you need to see in which plataform you are writing the file:

\ r = CR (carriage return) // Used as a newline character in Unix

\ n = LF (Line Feed) // Used as the new line character in Mac OS

\ r \ n = CR + LF // Used as a new line character in Windows

+1
source share

Try:

 file_put_contents($file, print_r($final_result, true), FILE_APPEND); 
0
source share

All Articles