Search code examples
phpcsvcarriage-return

Making CSV from PHP - Carriage return won't work


Seems like a fairly simple issue but can't get it to work. I am getting the user to download a csv file(which works fine).

Basically I can't get the carriage return to work.

header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=search_results.csv");
echo '"Name","Age"\n"Chuck Norris","70"';
exit;

Result : Name     Age\n"Chuck Norris"    70

Tried :

echo '"Name","Age",\n,"Chuck Norris","70"';

Result : Name     Age    \n    Chuck Norris    70

And

echo '"Name","Age",\n\r,"Chuck Norris","70"';

Result : Name     Age    \n\r    Chuck Norris    70

Know what's going wrong?


Solution

  • Regarding CSV, see the answer by Brenton. As for the "why it didn't work" answer:

    Yup, /n and similar only work in double-quotes :)

    e.g.

    echo '"Name","Age"' . "\n" . '"Chuck Norris","70"';
    

    or (this is gonna look awful)

    echo "\"Name\",\"Age\"\n\"Chuck norris\",\"79\"";
    

    but for readability sake:

     $nl = "\n";
       echo '"Name","Age"' . $nl .  '"Chuck Norris","70"';