-
Notifications
You must be signed in to change notification settings - Fork 1
/
CSVExport.php
68 lines (60 loc) · 1.63 KB
/
CSVExport.php
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
<?php
namespace serrg1994\csvexport;
use yii\base\Exception;
/**
* Class for export array data to csv file
*
*
* CSVExport::Export([
'dirName' => Yii::getAlias('@webroot'),
'fileName' => 'users.csv',
'data' => [
['#', 'User Name', 'Email'],
['1', 'Serhiy Novoseletskiy', '[email protected]']
]
]);
*/
class CSVExport
{
private static $data;
private static $dirName;
private static $fileName;
/**
* @param array $options
* @return string
* @throws \yii\base\Exception
*/
public static function Export(array $options = [])
{
static::$data = isset($options['data']) ? $options['data'] : [];
static::$fileName = isset($options['fileName']) ? $options['fileName'] : 'file.csv';
if (!isset($options['dirName'])) {
throw new Exception('You must set dirName');
}
static::$dirName = $options['dirName'];
if (static::$dirName[strlen(static::$dirName - 1)] !== '/') {
static::$dirName .= '/';
}
return self::array2csv(static::$data, static::$dirName, static::$fileName);
}
/**
* @param array $array
* @param $dirName
* @param $fileName
* @return string
*/
private static function array2csv(array &$array, $dirName, $fileName)
{
if (!is_dir($dirName)) {
mkdir($dirName);
}
ob_start();
$df = fopen($dirName . $fileName, 'w');
foreach ($array as $row) {
fputcsv($df, $row);
}
fclose($df);
ob_get_clean();
return $dirName . $fileName;
}
}