標籤:exception div hand iconv inpu 方法 logs color sub
<?php/** * Created by PhpStorm. * User: hanks * Date: 2017/4/30 * Time: 13:24 */include ‘header.php‘;include ‘Mysql.php‘;try{ $arr=[]; $mysql=new Mysql([]); $filename = $_FILES[‘file‘][‘tmp_name‘]; if(empty($filename)) { throw new Exception(‘請選擇要匯入的CSV檔案!‘,0); } $handle = fopen($filename, ‘r‘); $result = input_csv($handle); //解析csv $len_result = count($result); if($len_result==0){ throw new Exception(‘沒有任何資料!‘,0); } $data_values=‘‘; $date_time=time(); for ($i = 1; $i < $len_result; $i++) { //迴圈擷取各欄位值 $en_name = addslashes($result[$i][0]); //addslashes()方法 轉義mysql的特殊字元 $img_name = addslashes($result[$i][1]); $game_code = addslashes($result[$i][2]); $game_type = addslashes($result[$i][3]); $game_zh_name = addslashes(iconv(‘gbk‘, ‘utf-8‘, $result[$i][4])); //中文轉碼 $platform_type = addslashes($result[$i][5]); $data_values .= "(‘$en_name‘,‘$img_name‘,‘$game_code‘,‘$game_type‘,‘$game_zh_name‘,‘$platform_type‘,‘$date_time‘),"; } $data_values = substr($data_values,0,-1); //去掉最後一個逗號 fclose($handle); //關閉指標 $sql = "INSERT INTO `ks_game_list`(`en_game_name`,`game_src`,`code`,`game_type`,`game_name`,`platform_type`,`add_time`)values $data_values"; $rs=$mysql->doSql($sql); if($rs){ $arr=[‘status‘=>1,‘notice_content‘=>‘匯入成功!‘]; exit(json_encode($arr,true)); }else{ throw new Exception(‘匯入失敗!‘,0); }}catch(Exception $e){ $arr=[‘status‘=>$e->getCode(),‘notice_content‘=>$e->getMessage()]; exit(json_encode($arr,true));}function input_csv($handle) { $out = array (); $n = 0; while ($data = fgetcsv($handle, 10000)) { $num = count($data); for ($i = 0; $i < $num; $i++) { $out[$n][$i] = $data[$i]; } $n++; } return $out;}
php匯入csv檔案