Home » Php » PHP file_put_contents new line issue

PHP file_put_contents new line issue

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m unable to write array to text file in new lines. My code:

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

Output:

Array

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

Then:

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

Output:

Something1Something2Something3Array

My goal is:

Something1
Something2
Something3

Any ideas? 🙂

How to&Answers:

How about

file_put_contents($file, implode(PHP_EOL, $final_result), FILE_APPEND);

Answer:

Different platforms use different new-line characters. To over come this, php provides built in constant that takes care of them all: PHP_EOL

Answer:

Your array should be in this way to insert a new line after each value

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

Doing this:

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

You are inserting a new line after the complete array

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

\r = CR (Carriage Return) // Used as a new line character in Unix

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

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