php使用Linux命令导出MySQL数据到csv

PS :使用这个导出功能需要的条件:
1–服务器需要安装mysql客户端:yum install mysql
2–php需要开启exec函数(disable_functions exec)

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/**
* @FILE_NAME:ExcelExport.php
* @Description 数据导出excel,从数据库导出再下载,数据库配置
* [mysqld]
* secure_file_priv= ''
* @User ZHaoGuiBin
* @Date 2019-12-04 13:52:58
*/

class ExcelExport
{

/**
* @FuncName:exportExcel
* @Description
* @User ZHaoGuiBin
* @Date 2019-12-24 13:42:11
* @param string $title
* @param $sql
* @param $data
* @return bool
*/
public static function exportExcel($title = '报表导出', $sql, $data)
{

$data_dir = getcwd() . "/data_export/";

//去除sql语句里的`,要不然执行shell命令报错
$sql = str_replace('`', '', $sql);
$sql = str_replace('"', "'", $sql);

//删除历史表格
self::deleteExcel();

if (!file_exists($data_dir) || !is_writable($data_dir)) {
if (!@mkdir($data_dir, 0755, TRUE)) {
Tools::dieJs("alert('导出失败,请联系管理员处理');history.go(-1);");
}
}

$file_name = $title . time() . ".csv";
$temp_file_name = $title . time() . "_temp.csv";
$file_path = $data_dir . $file_name;
$temp_file_path = $data_dir . $temp_file_name;

//拼接sql
$fields = '';
$title_fields = '';
$temp_key = 0;
$fields_count = count($data);
foreach ($data as $key => $field) {
$temp_key += 1;
$fields .= "ifnull({$field},'') as {$field}" . ($temp_key < $fields_count ? ',' : '');
$title_fields .= "'{$key}'" . ($temp_key < $fields_count ? ',' : '');
}

$sql_str = "SELECT {$title_fields} UNION SELECT {$fields} FROM ({$sql}) as t";

$mysql_config = Yaf_Application::app()->getConfig()->toArray();
$mysql_config = $mysql_config['database']['config'];

// 2>&1 为了输出shell执行错误
$export_shell = 'mysql -h ' . $mysql_config['host'] . ' -P' . $mysql_config['port'] . ' -u' . $mysql_config['username'] . ' -p' . '"' . $mysql_config['password'] . '"' . ' ' . $mysql_config['dbname'] . ' --default-character-set=utf8 -e "' . $sql_str . '" | sed ' . "'" . 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' . "'" . ' > ' . $temp_file_path . ' 2>&1';
//文件转码
$iconv_shell = "iconv -f UTF-8 -t GB18030 {$temp_file_path} > {$file_path} 2>&1";

// dd($export_shell);

exec($export_shell, $output, $return_var);
exec($iconv_shell, $i_output, $i_return_var);
unlink($temp_file_path);

self::downloadExcel($file_path, $file_name);

return true;
}

/**
* @FuncName:downloadExcel
* @Description
* @User ZHaoGuiBin
* @Date 2019-12-24 14:25:10
* @param $file_path 文件地址
* @param $file_name 文件名称
* @return void
*/
public static function downloadExcel($file_path, $file_name)
{
ob_end_clean();

if (!file_exists($file_path)) {
Tools::dieJs("alert('文件不存在,请联系管理员处理');history.go(-1);");
}

$fp = fopen($file_path, "r");
$file_size = filesize($file_path);

//下载文件需要用到的头
header("Content-type:text/html;charset=utf-8");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length:" . $file_size);
Header("Content-Disposition: attachment; filename=" . $file_name);
$buffer = 1024;
$file_count = 0;

while (!feof($fp) && $file_count < $file_size) {
$file_con = fread($fp, $buffer);
$file_count += $buffer;
echo $file_con;
}
fclose($fp);
}

/**
* @FuncName:deleteExcel
* @Description 删除没用的表格
* @User ZHaoGuiBin
* @Date 2019-12-24 15:05:01
* @return bool
*/
public static function deleteExcel()
{

//几分钟前的时间戳
$delete_time = strtotime("-5 minute");

$data_dir = getcwd() . "/data_export/*.csv";
$data_dir = glob($data_dir);

if (empty($data_dir)) {
return true;
}

foreach ($data_dir as $key => $file_path) {
$temp_time = self::findNum($file_path);
if ($temp_time < $delete_time) {
unlink($file_path);
}
}

return true;
}

/**
* @FuncName:findNum
* @Description
* @User ZHaoGuiBin
* @Date 2019-12-24 14:54:11
* @param string $str
* @return string
*/
public static function findNum($str = '')
{
$str = trim($str);
if (empty($str)) {
return '';
}
$temp = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
$result = '';
for ($i = 0; $i < strlen($str); $i++) {
if (in_array($str[$i], $temp)) {
$result .= $str[$i];
}
}
return $result;
}


}