如何创建一个CSV文件
方法1 - 使用HTTP头
至于在Word和Excel,您需要添加头信息到PHP脚本的例子。
下面的代码片断创建一个指定的表包括其列名CSV文件。然后会提示用户下载此文件。
$table = 'table_name';
$outstr = NULL;
header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=cars-models.csv");
$conn = mysql教程_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("db",$conn);
// Query database to get column names
$result = mysql_query("show columns from $table",$conn);
// Write column names
while($row = mysql_fetch_array($result)){
$outstr.= $row['Field'].',';
}
$outstr = substr($outstr, 0, -1)." ";
// Query database to get data
$result = mysql_query("select * from $table",$conn);
// Write data rows
while ($row = mysql_fetch_assoc($result)) {
$outstr.= join(',', $row)." ";
}
echo $outstr;
mysql_close($conn);
?>
方法2 - 使用fputcsv()
在fputcsv()函数格式作为CSV行并将其写入一个打开的文件。欲了解更多信息,看
一看http://php.net/manual/en/function.fputcsv.php看看。
下面的代码片断创建一个指定表的列名,包括CSV文件,并将其发送到浏览器。
$table = 'table_name';
$filename = tempnam(sys_get_temp_dir(), "csv");
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("db",$conn);
$file = fopen($filename,"w");
// Write column names
$result = mysql_query("show columns from $table",$conn);
for ($i = 0; $i
$colArray[$i] = mysql_fetch_assoc($result);
$fieldArray[$i] = $colArray[$i]['Field'];
}
fputcsv($file,$fieldArray);
// Write data rows
$result = mysql_query("select * from $table",$conn);
for ($i = 0; $i
$dataArray[$i] = mysql_fetch_assoc($result);
}
foreach ($dataArray as $line) {
fputcsv($file,$line);
}
fclose($file);
header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=cars-models.csv");
// send file to browser
readfile($filename);
unlink($filename);
?>