通過PHP導出到CSV假設我有數據庫.。有什么方法可以通過PHP將數據庫中的內容導出到CSV文件(以及文本文件[如果可能的話])?
3 回答

鳳凰求蠱
TA貢獻1825條經驗 獲得超4個贊
function array2csv(array &$array){ if (count($array) == 0) { return null; } ob_start(); $df = fopen("php://output", 'w'); fputcsv($df, array_keys(reset($array))); foreach ($array as $row) { fputcsv($df, $row); } fclose($df); return ob_get_clean();}
function download_send_headers($filename) { // disable caching $now = gmdate("D, d M Y H:i:s"); header("Expires: Tue, 03 Jul 2001 06:00:00 GMT"); header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate"); header("Last-Modified: {$now} GMT"); // force download header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); // disposition / encoding on response body header("Content-Disposition: attachment;filename={$filename}"); header("Content-Transfer-Encoding: binary");}
download_send_headers("data_export_" . date("Y-m-d") . ".csv");echo array2csv($array);die();

當年話下
TA貢獻1890條經驗 獲得超9個贊
<?php $list = array ( array('aaa', 'bbb', 'ccc', 'dddd'), array('123', '456', '789'), array('"aaa"', '"bbb"'));$fp = fopen('file.csv', 'w');foreach ($list as $fields) { fputcsv($fp, $fields);}fclose($fp);?>

縹緲止盈
TA貢獻2041條經驗 獲得超4個贊
fputcsv
implode
// The data from Eternal Oblivion is an object, always$values = (array) fetchDataFromEternalOblivion($userId, $limit = 1000); // ----- fputcsv (slow)// The code of @Alain Tiemblo is the best implementationob_start();$csv = fopen("php://output", 'w'); fputcsv($csv, array_keys(reset($values)));foreach ($values as $row) { fputcsv($csv, $row);}fclose($csv);return ob_get_clean();// ----- implode (slow, but file size is smaller) $csv = implode(",", array_keys(reset($values))) . PHP_EOL;foreach ($values as $row) { $csv .= '"' . implode('","', $row) . '"' . PHP_EOL;}return $csv;// ----- concatenation (fast, file size is smaller) // We can use one implode for the headers =D$csv = implode(",", array_keys(reset($values))) . PHP_EOL;$i = 1; // This is less flexible, but we have more control over the formattingforeach ($values as $row) { $csv .= '"' . $row['id'] . '",'; $csv .= '"' . $row['name'] . '",'; $csv .= '"' . date('d-m-Y', strtotime($row['date'])) . '",'; $csv .= '"' . ($row['pet_name'] ?: '-' ) . '",'; $csv .= PHP_EOL;}return $csv;
- 3 回答
- 0 關注
- 495 瀏覽
添加回答
舉報
0/150
提交
取消