PHP导出CSV文件

  • 黄楚恒
  • 2017-08-28 14:21:35
  • PHP
  • CSV
<?php
//注意导出csv文件之前不能输出任何数据,否则失败
header('content-type:text/html;charset=utf-8');
//1.数据库取出数据  
$conn=mysql_connect('localhost','root','root');  
mysql_select_db('blog');
mysql_set_charset('utf8');
$result=mysql_query('select * from blog_user');  
$emps=array();  
while($row=mysql_fetch_assoc($result)){  
    static $i=0;  
    $emps[$i] = $row;  
    $i++;  
}  

//设置内存占用  
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','用户名','密码', '地址','用户注册时间','手机号码','性别1男,0女','邮箱','头像','QQ','生日','个性签名');  
fputcsv($output, $table_head);  
//输出每一行数据到文件中  
foreach ($emps as $e) {  
//    unset($e['xx']);//若有多余字段可以使用unset去掉  
//    $e['xx'] = isset($e['xxx']) ? "xx" : 'x'; //可以根据需要做相应处理  
    //输出内容  
    fputcsv($output, array_values($e));  
}  
// echo "<pre>";
// print_r($emps);exit;
 

Copyright © 2016-2019 709173702@qq.com 版权所有  ICP证粤ICP备16117826号-1
联系邮箱:709173702@qq.com