views:

238

answers:

2

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?

+4  A: 

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"';
Dan Heberden
worked! :) had to tweak it a little though -- echo "\"Name\",\"Age\"\n\"Chuck norris\",\"79\"";
DMin
Ah, i was wondering if you wanted those extra commas...
Dan Heberden
+3  A: 

As an alternative, probably more robust solution. PHP has a built in function (doesn't it always). fputcsv will write a correctly escaped csv line to a stream, if you're trying to output to the browser, you can use the standard output (stdout) stream instead of a file pointer.

eg.

$list = array (
  array('Name', 'Age'),
  array('Chuck Norris', 79)
);

foreach ($list as $line) {
    fputcsv(STDOUT, $line);
}
Brenton Alker
it also neatly and quietly deals with escaping of things like " in string values, and also automatically adds " around string sequences when you have whitespace, etc, in there.much better to use the library than reinvent the wheel
HorusKol