我有一个将值导出到 CSV 文件的功能,但是“评论”字段中有逗号,当您在电子表格程序中打开它时,它会弄乱列。
有没有办法正确导出它?
//this exports only names and comments into a CSV file
function exportNamesCommentsCSV($table, $columns) {
$file = "volunteer_comments";
$csv_output = '';
$table = 'volunteers_2009';
$result = mysql_query("select * FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT lname, fname, email, comments FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
}
编辑:这将是评论的一个例子......
我更喜欢在门口工作,但我真的可以在任何地方工作。
上面示例注释中的 ,(逗号)不符合正确的列结构。
最佳答案
您需要做的是将值括在引号中,如下所示:
"value","value","value"
这将正确处理值中的逗号,并且数值也仍然可以正常工作。
但是,要在值中加上引号,您需要将两个引号放在一起。例如。代表这个字符串:
Bobby says, "Hi!"
它需要表示为
"some value","Bobby says, ""Hi!""","Some other value"
你可以这样做:
$csv_value = "\"" . eregi_replace("\"", "\"\"", $orig_value) . "\"";
关于php - 如何正确导出到包含带逗号的表记录值的 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/555171/