首页 > 代码库 > php导入csv文件

php导入csv文件

<?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文件