开发者

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 :

ech开发者_如何学运维o '"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?


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"';


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜