Kris
Kris

Reputation: 1069

PHP file_put_contents new line issue

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? :)

Upvotes: 7

Views: 8987

Answers (3)

Rahul M
Rahul M

Reputation: 1509

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

Upvotes: 2

Phil
Phil

Reputation: 164760

How about

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

Upvotes: 17

Emilio Gort
Emilio Gort

Reputation: 3470

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

Upvotes: 1

Related Questions