可能的重复项:
用于将 MySQL 查询转换为 CSV 的 PHP 代码
我正在尝试导出CSV文件,我需要在打印的数据库字段之间创建空间,因为所有内容都是简单的行。
我需要做的是在标题中打印字段的名称..这是我拥有的代码。首先,我需要在 csv 选项卡中导出字段或只是字段之间的空格......
if ( !$result1 ) { echo mysql_error(); }
while ($row = mysql_fetch_array($result1)) {
$last = end($row);
foreach ($row as $item) {
fwrite($fh, $item);
if ($item != $last)
fwrite($fh, "'t");
}
fwrite($fh, "'n");
}
fclose($fh);
你可以考虑使用fputcsv,而不是fwrite的麻烦。语法是这样的:
int fputcsv ( resource $handle , array $fields [, string $delimiter = ',' [, string $enclosure = '"' ]] )
对于您的代码,它看起来像:
$fh = fopen('file.csv', 'w');
if ( !$result1 ) { echo mysql_error(); }
while ($row = mysql_fetch_array($result1)) {
fputcsv($fh, $result1, ',');
}
fclose($fh);
如果需要对字符串值使用其他引号(双引号是标准的),则可以使用可选的 $enclosure
参数。
在foreach 中试试这个
fwrite($fh,$item.,');
看看http://net.tutsplus.com/tutorials/php/how-to-generate-a-complete-excel-spreadsheet-from-mysql/