Montoolivo
Montoolivo

Reputation: 147

How to write on a new line in a text file using PHP?

I am trying to write in a text file using PHP. Every $result string must be on a new line in the txt file but when I am typing this all $result string is on the same line. What is the problem ?

Here is my code:

$result=date("Y.m.d").'!'.$_POST['name'].'!'.$_POST['price'].'!'.$selectedGroup."\n";
file_put_contents('data.txt', $result,FILE_APPEND)

Upvotes: 0

Views: 3120

Answers (3)

BlitZ
BlitZ

Reputation: 12168

Use PHP_EOL predefined constant:

file_put_contents('data.txt', $result . PHP_EOL, FILE_APPEND);

From manual:

PHP_EOL (string)

The correct 'End Of Line' symbol for this platform.

Available since PHP 4.3.10 and PHP 5.0.2

To test your input, you may try to output your file data with file() (it should properly determine line separations):

print_r(file('data.txt'));

If it contains more than one element, then your rows are separated.

Upvotes: 4

Slavic
Slavic

Reputation: 1962

How are you verifying the result? Are you opening up the file in an editor? If you are doing this on Windows, note that certain editors will show "\r\n" as a new line, while treating "\n" as a space or simply ignoring it.

Upvotes: 1

xdazz
xdazz

Reputation: 160833

The problem is that your editor (windows notepad?) doesn't treat \n as a new line.

There there kind of new lines

windows: \r\n

linux/unix: \n

mac: \r

Upvotes: 1

Related Questions