-1

I am making CSV file and I need to make a new line after each procedure. The standard \n\r doesn't work.

The code looks like:

while ($resultD=mysql_fetch_assoc($queryDown)) 
        {
            $csv.= $resultD["first_name"].' , '.$resultD["last_name"].' , '.$resultD["login"].' , '.$resultD["password"].'\n\r';
        }
        $filename= "export.csv";
        $theFile=fopen($filename,"w");
        fwrite($theFile, $csv);
esqew
  • 42,425
  • 27
  • 92
  • 132
Mego
  • 154
  • 1
  • 3
  • 10
  • 2
    ['\n\r' or "\r\n" there's some difference :)](https://eval.in/194725) – Jonny 5 Sep 17 '14 at 17:12
  • 1
    Perhaps [`fputcsv()`](http://php.net/fputcsv) and related functions would benefit you instead of trying to work with CSV more manually. – Wiseguy Sep 17 '14 at 17:14

3 Answers3

6

Use "\r\n", instead of '\n\r'.

You need the double quotes "" to recognize the escape sequences \r and \n. Single quotes won't do it.

EDIT

As Michael mentioned, you can also use PHP_EOL, again instead of '\n\r'.

This generates a newline character that is compatible across multiple platforms.


From PHP documentation on strings:

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

cppprog
  • 804
  • 3
  • 12
  • 22
  • 2
    There is `PHP_EOL` to do it in a platform-independent way, see stackoverflow question [When do I use the PHP constant “PHP_EOL”?](http://stackoverflow.com/questions/128560/when-do-i-use-the-php-constant-php-eol). – Michael Jaros Sep 17 '14 at 17:15
4

You could either use :

$csv .= '...' . "\r\n";

Or

$csv .= '...' . PHP_EOL;

Or give a look at fputcsv to get it work easily : http://php.net/manual/en/function.fputcsv.php

Clément Malet
  • 5,062
  • 3
  • 29
  • 48
0
$csv.= $resultD["first_name"].' , '.$resultD["last_name"].' , '.$resultD["login"].' , '.$resultD["password"]."\n";
Daimos
  • 1,473
  • 10
  • 28
  • 4
    Inclusion of an explanation is much more helpful than a code-only answer. – Wiseguy Sep 17 '14 at 17:16
  • 2
    Examples are helpful, but to exemplify what you are explaining. With just a code snippet, it's not immediately obvious what is different or _why_ it works. – Wiseguy Sep 17 '14 at 18:06