我正在编写一个PHP语句,该语句运行查询,然后将数据写入.csv文件。我遇到的问题是,我从服务器接收的一些数据中有逗号,这导致.csv文件在错误的位置输入数据。下面我有一个代码示例。
$sql = "Select *
From table;"
$data = mysqli_query($link, $sql);
$row= ("Column One, Column Two, Column Three'n");
while ($result = $data->fetch_assoc()) {
$row .= ("$result[columnOne], $result[columnTwo], $result[columnThree]'n");
}
$fd = fopen("./filePath.csv", "w") or die ("Error Message");
fwrite($fd, $row);
fclose($fd);
第三列是数据包含逗号的地方,逗号会导致数据写入.csv文件中的不同单元格。有什么解决方案可以使$result[columnThree]数据保持在一个单元格中,即使其中包含逗号?
您可以将值用双引号括起来:
$row .= ('"'.$result['columnOne'].'", "'.$result['columnTwo'].'", "'.$result['columnThree'].'"'n"');
我喜欢尽可能多地使用数组,而不是连接字符串:
$rawCsv = array();
while ($result = $data->fetch_assoc()) {
if (count($rawCsv) === 0)
$rawCsv[] = '"'.implode('","', array_keys($result )).'"';
$rawCsv[] = '"'.implode('","', $result ).'"';
}
$csvString = implode("'n", $rawCsv);
不过,这两种方法都很难在数据中使用不同的字符——双引号。考虑到这一点,一个更好的选择是使用fopen
和fputcsv
来创建CSV数据,而不必考虑它
如果你计划立即提供CSV数据供下载,你根本不需要文件,只需将其转储到输出黄油中即可:
ob_start();
$file_handle = fopen("php://output", 'w');
如果您确实想挂起一个文件,那么在所需的输出文件上使用fopen
,并跳过对ob_start
的调用
接下来,组装您的数据:
fputcsv($file_handle, array(
'Your',
'headings',
'here'
));
while ($result = $data->fetch_assoc()) {
fputcsv($file_handle, array(
$result['Your'],
$result['data'],
$result['"here"']
));
}
fclose($file_handle);
如果你正在使用一个文件,那么你已经准备好了!如果您正在使用输出缓冲区(未使用任何文件),则可以获取CSV数据并将其直接发送到浏览器:
$csv = ob_get_clean();
echo $csv; // should send headers first!
不过,要小心输出缓冲,有些框架/应用程序会在内部使用它。如果遇到问题,请尝试使用文件。如果该文件有效,那么您的框架可能已经在使用输出缓冲区了。
文档
- RFC 4180逗号分隔值(CSV)文件的通用格式和MIME类型-https://www.rfc-editor.org/rfc/rfc4180
implode
-http://php.net/function.implodefopen
-http://php.net/manual/en/function.fopen.phpfclose
-http://php.net/manual/en/function.fclose.phpfputcsv
-http://php.net/manual/en/function.fputcsv.phpob_start
-http://php.net/manual/en/function.ob-start.phpob_get_clean
-http://php.net/manual/en/function.ob-get-clean.php