Writing a new line to file in PHP (line feed)

352,905

Solution 1

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").

Solution 2

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

Solution 3

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

Solution 4

You can also use file_put_contents():

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);
Share:
352,905
VIVA LA NWO
Author by

VIVA LA NWO

Updated on April 29, 2020

Comments

  • VIVA LA NWO
    VIVA LA NWO about 4 years

    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.

  • Alix Axel
    Alix Axel over 11 years
    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).
  • csonuryilmaz
    csonuryilmaz about 9 years
    I have changed "\r\n" to "\n" for my line ending amd it worked. Thanks.
  • Mr PizzaGuy
    Mr PizzaGuy over 4 years
    now my code uses both " and ' and it bothers me
  • DarkVeneno
    DarkVeneno almost 4 years
    In fact, you can actually notice that \n gets highlighted when using "" but not when using ' '. (This is, if your editor uses syntax highlighting, mine is Sublime Text 3)
  • Sami Haroon
    Sami Haroon over 3 years
    This is the best answer. more dynamic, and handles fopen(), fwrite(), fclose() by itself.
  • Christian
    Christian almost 3 years
    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. grobmeier.solutions/…
  • cachius
    cachius about 2 years
    Might perform better when the file is on a ramdisk.