129

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);

For some reason, it's writing \n as a string, so the file looks like this:

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

From Google'ing it tells me to use \r\n, but \r is a carriage return which doesn't seem to be what I want to do. I just want the file to look like this:

40119
40122
40120
42155
36925
45881
42145
45880

Thanks.

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
VIVA LA NWO
  • 3,852
  • 6
  • 24
  • 21

4 Answers4

314

Replace '\n' with "\n". The escape sequence is not recognized when you use '.

See the manual.

For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopen should get "wb", not "w").

Artefacto
  • 96,375
  • 17
  • 202
  • 225
76

PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:

Using this will save you extra coding on cross platform developments.

IE.

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

If you looped through this twice you would see in 'somefile':

some data
some data
user1649798
  • 873
  • 7
  • 8
  • 2
    You should fclose after you done with file : https://www.php.net/manual/en/function.fclose.php – hendr1x Aug 30 '22 at 14:00
  • For anybody (like me) who did not see any change it's the `a` (append) instead of `w` (write) `$fp = fopen('somefile', 'a');` – Lepy Dec 15 '22 at 21:22
73

Use PHP_EOL which outputs \r\n or \n depending on the OS.

hakre
  • 193,403
  • 52
  • 435
  • 836
Aldarien
  • 731
  • 5
  • 2
  • 5
    Don't get in trouble, always use `\n` unless you want to open the file in a specific OS - if so, use the newline combination of that OS, and not the OS you're running PHP on (`PHP_EOL`). – Alix Axel Oct 09 '12 at 13:35
43

You can also use file_put_contents():

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • 1
    This is the best answer. more dynamic, and handles fopen(), fwrite(), fclose() by itself. – Sami Haroon Oct 06 '20 at 06:58
  • 1
    That's good for few writes, but when you want to do a lot of writes (i.e. in a loop) you may consider fopen/fwrite/fclose for performance reasons. https://grobmeier.solutions/performance-ofnonblocking-write-to-files-via-php-21082009.html – Christian May 15 '21 at 09:44
  • Might perform better when the file is on a ramdisk. – cachius Feb 10 '22 at 10:35