Coder Perfect

In PHP, add a new line to the file (line feed)

Problem

My code:

$i = 0;
$file = fopen('ids.txt', 'w');
foreach ($gemList as $gem)
{
    fwrite($file, $gem->getAttribute('id') . '\n');
    $gemIDs[$i] = $gem->getAttribute('id');
    $i++;
}
fclose($file);

It’s writing n as a string for some reason, so the file looks like this:

40119\n40122\n40120\n42155\n36925\n45881\n42145\n45880

According to Google, I should use rn, but r is a carriage return, which isn’t what I want to accomplish. All I need is for the file to look like this:

40119
40122
40120
42155
36925
45881
42145
45880

Thanks.

Asked by VIVA LA NWO

Solution #1

‘n’ should be replaced with “n.” When you use ‘, the escape sequence is not recognized.

See the manual.

See this note for information on how to write line endings. In general, different operating systems have different line-ending conventions. “rn” is used by Windows, while “n” is used by Unix-based operating systems. Stick to one naming scheme (I’d go with “n”) and open your file in binary mode (fopen should get “wb”, not “w”).

Answered by Artefacto

Solution #2

Use PHP EOL, which produces rn or n depending on the operating system.

Answered by Aldarien

Solution #3

Since PHP 4.3.10 and PHP 5.0.2, PHP EOL has been a predefined constant. See the following manual posting:

This will save you time and effort when developing cross-platform applications.

IE.

$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);

If you looped this twice, you’d get the following in’somefile’:

some data
some data

Answered by user1649798

Solution #4

You can also use file put contents() to get the contents of a file:

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);

Answered by Alix Axel

Post is based on https://stackoverflow.com/questions/3066421/writing-a-new-line-to-file-in-php-line-feed