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
提交
取消