PHP代码将MySQL查询转换为CSV请问在PHP中将MySQL查询转换为CSV的最有效方法是什么?最好避免临时文件,因为这降低了可移植性(dir路径和设置所需的文件系统权限)。CSV还应该包括一行字段名。
3 回答
守候你守候我
TA贡献1802条经验 获得超10个赞
$result = $db_con->query('SELECT * FROM `some_table`');if (!$result) die('Couldn\'t fetch records');$num_fields = mysql_num_fields($result);$headers = array();for ($i = 0; $i < $num_fields; $i++) { $headers[] = mysql_field_name($result , $i);}$fp = fopen('php://output', 'w');if ($fp && $result) { header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="export.csv"'); header('Pragma: no-cache'); header('Expires: 0'); fputcsv($fp, $headers); while ($row = $result->fetch_array(MYSQLI_NUM)) { fputcsv($fp, array_values($row)); } die;}
森栏
TA贡献1810条经验 获得超5个赞
$result = mysql_query('SELECT * FROM `some_table`'); if (!$result) die('Couldn\'t fetch records'); $num_fields = mysql_num_fields($result); $headers = array(); for ($i = 0; $i < $num_fields; $i++) { $headers[] = mysql_field_name($result , $i); } $fp = fopen('php://output', 'w'); if ($fp && $result) { header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="export.csv"'); header('Pragma: no-cache'); header('Expires: 0'); fputcsv($fp, $headers); while ($row = mysql_fetch_row($result)) { fputcsv($fp, array_values($row)); }die; }
添加回答
举报
0/150
提交
取消