PHP文件生成CSV,如何正确输出文本
目前我正在编写一个 PHP 脚本,用于从 MySQL 数据库中的条目输出 CSV 文件。我的问题在于如何正确输出值。 MySQL 数据库中的许多条目将包含逗号和引号,如果我只是简单地将它们打印到文件中,则会破坏 CSV 文件的格式。
我知道我可以用引号将文本引起来,但是包含引号的条目会弄乱文件的格式。
我的问题是,我能做些什么来防止这种情况发生?
另外,新行会影响文件的解释吗?
另外,我不想在 PHP 中使用 fputcsv 函数。我试图让 PHP 脚本输出文件的内容(带有适当的标头),而不是写入新文件。
提前致谢!
问候, 天球
Currently I am working on a PHP script to output a CSV file from entries in a MySQL database. My problem lies in how to correctly output the values. Many of the entries in the MySQL database will contain commas and quotes, which destroy the format of the CSV file if I just plainly print them out to the file.
I'm aware that I can surround the text in quotes, but the entries that contain quotes would mess up the format of the file.
My question is, what can I do to keep this from happening?
Also, do new lines affect the interpretation of the file?
In addition, I'd rather not use the fputcsv function in PHP. I'm attempting to make the PHP script output the contents of the file (with appropriate headers) rather than write to a new file.
Thanks in advance!
Regards,
celestialorb
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您对 fputcsv 的解雇可能还为时过早。在 fputcsv 手册的注释中,有一个示例,他们使用 fputcsv 输出到浏览器而不是文件。
http://php.net/manual/en/function.fputcsv.php
下面是该代码,加上一些标头,表明它确实提示用户下载 csv 文件。
I think your dismissal of fputcsv might have been premature. In the comments of the fputcsv manual there's an example where they use fputcsv to output to the browser instead of a file.
http://php.net/manual/en/function.fputcsv.php
Here is that code, plus some headers to show that it does indeed prompt the user to download a csv file.
该过程称为转义,大多数解析器(包括 PHP)使用反斜杠来转义字符:
您可以使用
addcslashes
:给定一个要用逗号分隔的数据数组,您可以执行以下操作:
The process is called escaping, and most parsers (included PHP's) use the backslash to escape characters:
You can escape characters in a string with
addcslashes
:Given an array of data you want to separate by commas, you can do the following:
我发现制表符分隔的值文件在这些情况下很有帮助。 TSV 不太容易受到数据中逗号等问题的影响。
I have found tab separated value files to be helpful in these situations. TSV is less susceptible to the issues with commas etc in your data.