php 导出csv文件方法
public static function exportCsv($data, $titleArr, $fileName = '') {
$csv_data = '';
/** 标题 */
$nums = count($titleArr);
for ($i = 0; $i < $nums - 1; ++$i) {
$title = '"' . $titleArr[$i] . '",';
$csv_data .= iconv('UTF-8', 'GBK', $title);
}
if ($nums > 0) {
$title1 = '"' . $titleArr[$nums - 1] . "\"\r\n";
$csv_data .= iconv('UTF-8', 'GBK', $title1);;
}
foreach ($data as $k => $row) {
for ($i = 0; $i < $nums - 1; ++$i) {
$row[$i] = iconv('UTF-8', 'GBK', $row[$i]);
$row[$i] = str_replace("\"", "\"\"", $row[$i]);
$csv_data .= '"' . $row[$i] . '",';
}
$csv_data .= iconv('UTF-8', 'GBK', '"' . $row[$nums - 1] . "\"\r\n");;
unset($data[$k]);
}
header('Content-Type: text/csv; charset=UTF-8');
//取数组最后一个元素,得到文件类型
$uploaddir = public_path() .'upload/phpExcel/syncFile/';//设置文件保存目录注意包含
if (!file_exists($uploaddir)) {
mkdir($uploaddir, 0700, true);
}
$path = $uploaddir. $fileName;
$file_name = empty($path) ? date('Y-m-d-H-i-s', time()) : $path;
file_put_contents($file_name, $csv_data);
return $file_name;