November 9, 2017 09:25:56
According to the project practice summary of a class file, Mac/win not garbled
English default from gb2312 to Utf-8
Https://gitee.com/myDcool/PHP-CSV
Usage:
1 // Import: 2 $arr = Csv::import ($filepath); 3 4 // Export: 5 $data = [' filename ' = ' xxx ', ' list ' = [[Xx,xx,x], [Xx,xx,X]]; 6 csv::export ($data);
1<?PHP2 3 classCSV4 {5 Public Static $csvError= ' ';6 7 Public Static function_seterror ($error)8 {9Self::$csvError=$error;Ten } One A /** - * Read csv file array - * @param string $filePath file path the * @return Array|bool - */ - Public Static functionImport$filePath) - { + setlocale(Lc_all, ' ZH_CN '); - + if(!file_exists($filePath) || !is_readable($filePath)) { ASelf::_seterror (' File not present or unreadable ')); at return FALSE; - } - - $rows=Array(); - $fp=fopen($filePath, ' RB '); - while(!feof($fp)) { in - $row=Str_replace(Array("\ r \ n", "\ r", "\ n"), ",fgets($fp)); to $rows[] =Explode(‘,‘,Iconv(' GB2312 ', ' UTF-8 ',$row));//Simplified Chinese encoding to Utf-8, GBK compatible gb2312 + - } the return $rows; * } $ Panax Notoginseng /** - * Output UTF-8 encoded CSV file the * @param array $data [' filename ' = ' xxx ', ' list ' = [[Xx,xx,x], [xx,xx,x], ... ] + * @return BOOL A */ the Public Static functionExport$data) + { - if(Empty($data[' filename ']) ||Empty($data[' List '])) { $Self::_seterror (' Missing parameter filename/list '); $ return FALSE; - } - $filename=$data[' filename '];//file name the - Header("expires:0");Wuyi Header("Cache-control:max-age=0, No-cache, Must-revalidate, Proxy-revalidate"); the //Force Download - Header("Content-type:application/force-download"); Wu Header("Content-type:application/octet-stream"); - Header("Content-type:application/download"); About //disposition/encoding on response body $ Header("content-disposition:attachment;filename={$filename}"); - Header("Content-transfer-encoding:binary"); - - //set Utf-8 + BOM to handle garbled characters display A Echo(CHR(0xEF).CHR(0xBB).CHR(0xBF)); + the //Open Output Cache - Ob_start(); $ the //Open the output stream the $DF=fopen("Php://output", ' W '); the the //Data Write Cache - foreach($data[' List '] as $row) { in foreach($row as $k=$v) { the Is_numeric($v) && ($row[$k]. = "\ t");//prevent turns into scientific counting method display the } AboutFputcsv ($DF,$row); the } the the fclose($DF); + Echo Ob_get_clean(); - Exit; the }Bayi}
View Code
PHP Import and export CSV file