php 导出csv表格文件

1.数据库取出数据,存放在二维数组中

$conn=new mysqli('localhost','root','root','myDBPDO');  
$result=$conn->query('select * from emp');  
$emps=array();  
while($row=$result->fetch_assoc()){  
    static $i=0;  
    $emps[$i] = $row;  
    $i++;  
}  

2.输出csv数据(表头及内容)

//设置内存占用  
set_time_limit(0);  
ini_set('memory_limit', '512M');  
  
//为fputcsv()函数打开文件句柄  
$output = fopen('php://output', 'w') or die("can't open php://output");  
//告诉浏览器这个是一个csv文件  
$filename = "员工信息表" . date('Y-m-d', time());  
header("Content-Type: application/csv");  
header("Content-Disposition: attachment; filename=$filename.csv");  
//输出表头  
$table_head = array('id','姓名','年龄', '薪水');  
fputcsv($output, $table_head);  
//输出每一行数据到文件中  
foreach ($emps as $e) {  
//    unset($e['xx']);//若有多余字段可以使用unset去掉  
//    $e['xx'] = isset($e['xxx']) ? "xx" : 'x'; //可以根据需要做相应处理  
    //输出内容  
    fputcsv($output, array_values($e));
   o
b_flush();
flush();
}

3.关闭句柄

fclose($output);
unset($emps);
ob_flush();
flush();
exit();    

其中iconv('utf-8', 'gbk', $a);在遍历时,如有需要可用于转码