从 PHP 制作 CSV - 回车符不起作用
看起来是一个相当简单的问题,但无法让它发挥作用。我让用户下载一个 csv 文件(效果很好)。
基本上我无法让回车正常工作。
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=search_results.csv");
echo '"Name","Age"\n"Chuck Norris","70"';
exit;
结果: 姓名 年龄\n“Chuck Norris” 70
尝试过:
echo '"Name","Age",\n,"Chuck Norris","70"';
结果: 姓名 ; 年龄 \n 查克·诺里斯 70
结果
echo '"Name","Age",\n\r,"Chuck Norris","70"';
:姓名 年龄 \n\r Chuck Norris 70
知道出了什么问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于CSV,请参阅Brenton的回答。至于“为什么它不起作用”的答案:
是的,/n和类似的东西只能用双引号:)
例如
或(这看起来很糟糕),
但为了可读性:
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.
or (this is gonna look awful)
but for readability sake:
作为替代方案,可能是更强大的解决方案。 PHP 有一个内置函数(并非总是如此)。 fputcsv 会将正确转义的 csv 行写入流,如果您尝试输出到浏览器时,可以使用标准输出(stdout)流而不是文件指针。
例如。
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.