php导出CSV

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
//导出的首行标题以及需要导出的字段
$parm = array(
"公司名称"=>'business_name',
'公司城市'=>'province',
'公司地址'=>'detail_addr_'
);

/**
* 导出CSV文件
* @param array $data 数据
* @param array $header_data 首行数据
* @param string $file_name 文件名称
* @param string $body_data 需要导出的字段名
* @return string
*/
public function export_csv($data = [], $parm = [], $file_name = '')
{
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename='.$file_name);
header('Cache-Control: max-age=0');
$fp = fopen('php://output', 'a');
$header_data = array_keys($parm);
$body_data = array_values($parm);

if (!empty($header_data)) {
foreach ($header_data as $key => $value) {
$header_data[$key] = iconv('utf-8', 'gbk', $value);
}
fputcsv($fp, $header_data);
}
$num = 0;
$limit = 100000;
//逐行取出数据,不浪费内存
$count = count($data);
if ($count > 0) {
for ($i = 0; $i < $count; $i++) {
$num++;
//刷新一下输出buffer,防止由于数据过多造成问题
if ($limit == $num) {
ob_flush();
flush();
$num = 0;
}
$row = [];
$export_data = $data[$i];
foreach ($export_data as $key => $value) {
if(!in_array($key,$body_data)){
continue;
}else{
foreach($body_data as $key1=>$value1){
$row[$value1] = iconv('utf-8', 'gbk', $export_data[$value1]);
}

}
}
fputcsv($fp, $row);
}
}
fclose($fp);
}


public function export_csv_1($data = [], $header_data = [], $file_name = '')
{
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $file_name);
if (!empty($header_data)) {
echo iconv('utf-8','gbk//TRANSLIT','"'.implode('","',$header_data).'"'."\n");
}
foreach ($data as $key => $value) {
$output = array();
$output[] = $value['id'];
$output[] = $value['name'];
echo iconv('utf-8','gbk//TRANSLIT','"'.implode('","', $output)."\"\n");
}
}