fputcsv
function array2csv(array &$array,$head)
{
if (count($array) == 0) {
return null;
}
ob_start();
$df = fopen("php://output", 'w');
if(!$head){
$head=array_keys(reset($array));
}
fputcsv($df,$head);
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");
}
/要生成csv文件的数组http://phpff.com/1076.html
$csvArr=[['编号1','周杰伦','台湾','歌手'],['编号2','王菲','北京','歌手']];
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
$head=array('编号','名字','地区','职业');
echo array2csv($csvArr,$head);
逗号拼接
function array2csv($array,$head){
$s=implode(',', $head).PHP_EOL;
echo iconv('utf-8','GBK//IGNORE',$s);
foreach ($array as $key => $value) {
$s=implode(',', $value).PHP_EOL;
echo iconv('utf-8','GBK//IGNORE',$s);
}
}
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($csvArr,$head);
基于 laravel 的 excel 扩展
//https://packagist.org/packages/maatwebsite/excel
composer require "maatwebsite/excel:~2.1.0"
vi config/app.php
Maatwebsite\Excel\ExcelServiceProvider::class,
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
function arraytoexecl($array,$head){
array_unshift($array,$head);
Excel::create('data_export_'.date('YmdHis'), function($excel) use($array){
$excel->sheet('Sheetname', function($sheet) use($array) {
$sheet->fromArray($array, null, 'A1', false, false);
});
})->export('xlsx');
}