将由PHP fputcsv()生成的CSV值与“ “, [英] Wrap CSV values generated by PHP fputcsv() with " "

查看:122
本文介绍了将由PHP fputcsv()生成的CSV值与“ “,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我的代码使用PHP的内置 <$ c生成一个CSV文件$ c> fputcsv 函数。

So, my code generates a CSV file using PHP's built-in fputcsv function.

对于分隔符,我使用','(逗号)。

对于机箱,我使用''''(双引号)。

For the delimiter, I use ',' (a comma).
For the enclosure, I use '"' (a double-quote).

但是,当我尝试类似

fputcsv($file,array('a','b',"long string, with commas",NULL,''),',','"');

它输出

a,b,"long string, with commas",,

喜欢输出

"a","b","long string, with commas","",""

有一个简单的方法来处理这个,或者我必须写一个替换 fputcsv

Is there an easy way to deal with this, or would I have to write a replacement for fputcsv?

推荐答案

这通常不是CSV文件的问题。

This is not usually a problem for CSV files.

fputcsv在值周围加引号,如果它不明确。例如,

fputcsv puts quotes around the value if it would be ambiguous. For example,

a,b,"long string, with commas",,

不含糊,但

a,b,long string, with commas,,

CSV解析器将接受字符串字面量,即使没有引号。

CSV parsers will accept string literals even without quotes around them.

如果你想要引用值的话,下面的代码片段。它不会在字符串中转义引号 - 这个练习是留给读者:

If you want quotes around the values anyway, the following snippet would do that. It doesn't escape quotes inside the string - that exercise is left to the reader:

$row = '"' . implode('", "', $rowitems) . '"';

您会希望将此结果放入所有行的循环中。

You would want to put this in a loop for all your rows.

这篇关于将由PHP fputcsv()生成的CSV值与“ “,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆