本篇文章給大家帶來的內容是關於php如何匯出csv檔案(程式碼範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。
/** 如果大量資料匯出 支援分頁寫入 * [DownloadDate 公用匯出csv] * @param string $name [檔案名稱] * @param array $header [表頭] * @param array $data [資料集] * @param $is_header [真 假 是否取表頭 解決迴圈寫入問題] * @return array name[檔案名稱] filePath[檔案路徑] */public static function DownloadData($name='',$header=array(),$data=array(),$is_header=true){ set_time_limit(0); ini_set('memory_limit','2048M'); header("Content-type:application/vnd.ms-excel"); header("content-Disposition:filename=downloaded.pdf "); try { if (!$name || !$data) { throw new BadRequestHttpException('參數不可為空白'); } $filePath = "./temp/download/{$name}.csv"; $header = implode(",",$header); $header = iconv('UTF-8', 'GBK//IGNORE', $header); $header = explode(",", $header); $fp = fopen($filePath, 'a+'); if (!empty($header) && is_array($header) && $is_header) { fputcsv($fp, $header); } foreach ($data as $row) { $str = implode("@@@@",$row); $str = iconv('UTF-8', 'GBK//IGNORE', $str); $str = str_replace(",","|",$str); $row = explode("@@@@", $str); fputcsv($fp, $row); } unset($data); if(ob_get_level()>0){ ob_flush(); } flush(); } catch (Exception $e) { throw new BadRequestHttpException($e->getMessage());//拋出異常 } return [ 'filePath'=>ltrim($filePath,"./"), 'name'=>$name.'.csv', ]; }