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
| function write_csv_file($file_path, $datas = [], $separator = ',', $enclosure = '"', $escape = '"'){ if (empty($datas)){ throw new Exception("empty datas"); } if (!file_exists($file_path)){ $dirname = pathinfo($file_path, PATHINFO_DIRNAME); if (!is_dir($dirname)){ mkdir(iconv('UTF-8','GBK', $dirname), 0777, true); } }
$title = array_keys($datas[0]); $no_title = true; $col = 0; foreach($title as $t){ if ($t != $col){ $no_title = false; break; } $col++; }
$handle = fopen($file_path, 'w'); if (!$no_title){ fputcsv($handle, $title, $separator, $enclosure, $escape); }
foreach($datas as $data){ $content = []; foreach($data as $txt){ if (!is_numeric($txt) && strtotime($txt) != false) { $content[] = ' '.$txt; }else{ $content[] = $txt; } } fputcsv($handle, $content, $separator, $enclosure, $escape); } fclose($handle); }
|