-
-
/**
- * php header导入csv文件
- * 编辑:bbs.it-home.org
- */
- header('Content-type:text/html;charset=utf-8;');
- @date_default_timezone_set('Asia/Shanghai');
- @error_reporting(E_ALL);
- @ini_set('display_errors', 'On');
- @ini_set('memory_limit', '512M');
- define('DB_HOST', 'localhost');
- define('DB_USER', 'root');
- define('DB_PASS', '');
- define('DB_NAME', 'DB_XXX');
//批量导入csv格式数据并生成导入sql文件
- //csv文件列为 省(province、city、area、position、address),注意要和数据库字段对应
- $sql_list = array();
- foreach(array(
- 'chongqing.csv' => array('name' => '重庆市','sort' => 4),
- 'guizhou.csv' => array('name' => '贵州省','sort' => 24),
- 'shanghai.csv' => array('name' => '上海','sort' => 2),
- 'sichuan.csv' => array('name' => '四川省','sort' => 23),
- 'yunnan.csv' => array('name' => '云南省','sort' => 25)
- ) as $filename => $_data) {
- $sql = $sql_start = "INSERT INTO `Tbl_Data` (`province`,`city`,`area`,`position`,`address`,`sort`) VALUES ";
- $handle = fopen($filename,'r');
- $i=0;
- echo '
'; Salin selepas log masuk
- while( $row = fgetcsv($handle,1000,',') ){
- if(!$row) continue;
- if($i $sql .= "('".iconv('gbk','utf-8',trim($row[0]))."','".iconv('gbk','utf-8',trim($row[1]))."','".iconv('gbk','utf-8',trim($row[2]))."','".iconv('gbk','utf-8',trim($row[3]))."','".iconv('gbk','utf-8',trim($row[4]))."','".$_data['sort']."'),";
- }else{
- break;
- }
- $i++;
- }
- $sql = rtrim($sql,',');
- $sql_list[] = $sql;
- $csv = 'csv_import_'.$filename.'_'.date('Y-m-d').'.sql';
- $csv_arr[] = $csv;
- $write_result = file_put_contents($csv,implode("\n\n",$sql_list));
- if($write_result){
- echo $csv."文件生成成功。\n";
- }else{
- echo $csv."文件写入失败!!!\n";
- }
}
//写入数据库(php导入csv文件生成的sql文件)
- $lnk = mysql_connect(DB_HOST, DB_USER, DB_PASS);
- mysql_select_db(DB_NAME, $lnk);
- mysql_query('SET SQL_MODE=""', $lnk);
- mysql_query('SET NAMES utf8', $lnk);
- $i = 0;
- foreach($sql_list as $sql) {
- $query_result = mysql_query($sql,$lnk);
- if($query_result){
- echo '写入数据:';
- echo $csv_arr[$i]."数据写入成功。\n\r";
- }else{
- echo '写入数据失败';
- echo $csv_arr[$i]."数据写入失败!!!\n\r";
- }
- $i++;
- }
- mysql_close($lnk);
- unset($sql,$sql_list,$write_result,$csv_arr,$query_result,$lnk);
- ?>
-
复制代码
|