php匯入csv檔案

來源:互聯網
上載者:User

標籤: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檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.