//数据库连接
$host="localhost";
$uname="root";
$pass="";
$database = "xyz";
$connection=mysql_connect($host,$uname,$pass);
echo mysql_error();
//或死亡(“数据库连接失败”);
$selectdb=mysql_select_db($database) or die("Database could not be selected");
$result=mysql_select_db($database)
or die("database cannot be selected <br>");
//从数据库中获取记录
$output = "";
$table = ""; // Enter Your Table Name
$sql = mysql_query("select * from $table");
$columns_total = mysql_num_fields($sql);
//获取字段名称
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
//从表中获取记录
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
//下载文件
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
答案 0 :(得分:0)
创建连接并使用以下代码在PHP中生成CSV。
$result = mysqli_query ($mysqliConn,"SELECT * FROM core ORDER BY start_datetime ASC");
$fields = mysqli_fetch_fields($result);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_fetch_fields($result);
$headers = array();
foreach ($fields as $field) {
$headers[] = $field->name;
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="core.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
希望这有帮助。