-
-
/** - * php header import csv file
- * Editor: 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');
//Batch import csv Format data and generate imported sql files
- //The csv file is listed as province (province, city, area, position, address), pay attention to correspond to the database fields
- $sql_list = array();
- foreach(array(
- 'chongqing. csv' => array('name' => 'Chongqing City','sort' => 4),
- 'guizhou.csv' => array('name' => 'Guizhou Province',' sort' => 24),
- 'shanghai.csv' => array('name' => 'Shanghai','sort' => 2),
- 'sichuan.csv' => array(' name' => 'Sichuan Province','sort' => 23),
- 'yunnan.csv' => array('name' => 'Yunnan Province','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 '
';
- while( $row = fgetcsv($handle,1000,',') ){
- if(!$row) continue;
- if($i<1000000){
- $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("nn",$sql_list));
- if($write_result){
- echo $csv."File generation successful. n";
- }else{
- echo $csv."File writing failed! ! ! n";
- }
}
//Write to database (sql file generated by importing csv file by php)
- $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 'Write data:';
- echo $csv_arr[$i]."Data written successfully . nr";
- }else{
- echo 'Failed to write data';
- echo $csv_arr[$i]."Failed to write data! ! ! nr";
- }
- $i++;
- }
- mysql_close($lnk);
- unset($sql,$sql_list,$write_result,$csv_arr,$query_result,$lnk);
- ?>
-
Copy code
|