CsvHelper.php
1.77 KB
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
<?php
namespace app\ht\helpers;
use function count;
use function ob_start;
use function fopen;
use function iconv;
use function fputcsv;
use function fclose;
use function ob_get_clean;
use function gmdate;
use function header;
/**
* Class CsvHelper
* @package app\ht\helpers
*/
class CsvHelper
{
/**
* @param array $array
* @return null|string
*/
protected static function array2csv(array &$array)
{
if (count($array) == 0) {
return null;
}
ob_start();
$df = fopen("php://output", 'w');
foreach ($array as $row) {
foreach ($row as $i => $v) {
$row[$i] = iconv('utf-8', 'gbk', $v);
}
fputcsv($df, $row);
}
fclose($df);
return ob_get_clean();
}
/**
* @param $filename
*/
protected static function downloadSendHeaders($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");
}
/**
* @param array $array
* @param $filename
*/
public static function export(array &$array, $filename)
{
self::downloadSendHeaders($filename . ".csv");
echo self::array2csv($array);
die();
}
}