当前位置:Gxlcms > PHP教程 > php导入csv到sql文件自动插入数据库(示例)

php导入csv到sql文件自动插入数据库(示例)

时间:2021-07-01 10:21:17 帮助过:26人阅读

  1. /**

  2. * php header导入csv文件
  3. * 编辑:bbs.it-home.org
  4. */
  5. header('Content-type:text/html;charset=utf-8;');
  6. @date_default_timezone_set('Asia/Shanghai');
  7. @error_reporting(E_ALL);
  8. @ini_set('display_errors', 'On');
  9. @ini_set('memory_limit', '512M');
  10. define('DB_HOST', 'localhost');
  11. define('DB_USER', 'root');
  12. define('DB_PASS', '');
  13. define('DB_NAME', 'DB_XXX');

  14. //批量导入csv格式数据并生成导入sql文件

  15. //csv文件列为 省(province、city、area、position、address),注意要和数据库字段对应
  16. $sql_list = array();
  17. foreach(array(
  18. 'chongqing.csv' => array('name' => '重庆市','sort' => 4),
  19. 'guizhou.csv' => array('name' => '贵州省','sort' => 24),
  20. 'shanghai.csv' => array('name' => '上海','sort' => 2),
  21. 'sichuan.csv' => array('name' => '四川省','sort' => 23),
  22. 'yunnan.csv' => array('name' => '云南省','sort' => 25)
  23. ) as $filename => $_data) {
  24. $sql = $sql_start = "INSERT INTO `Tbl_Data` (`province`,`city`,`area`,`position`,`address`,`sort`) VALUES ";
  25. $handle = fopen($filename,'r');
  26. $i=0;
  27. echo '
    ';
  28. while( $row = fgetcsv($handle,1000,',') ){
  29. if(!$row) continue;
  30. if($i<1000000){
  31. $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']."'),";
  32. }else{
  33. break;
  34. }
  35. $i++;
  36. }
  37. $sql = rtrim($sql,',');
  38. $sql_list[] = $sql;
  39. $csv = 'csv_import_'.$filename.'_'.date('Y-m-d').'.sql';
  40. $csv_arr[] = $csv;
  41. $write_result = file_put_contents($csv,implode("\n\n",$sql_list));
  42. if($write_result){
  43. echo $csv."文件生成成功。\n";
  44. }else{
  45. echo $csv."文件写入失败!!!\n";
  46. }

  47. }

  48. //写入数据库(php导入csv文件生成的sql文件)

  49. $lnk = mysql_connect(DB_HOST, DB_USER, DB_PASS);
  50. mysql_select_db(DB_NAME, $lnk);
  51. mysql_query('SET SQL_MODE=""', $lnk);
  52. mysql_query('SET NAMES utf8', $lnk);
  53. $i = 0;
  54. foreach($sql_list as $sql) {
  55. $query_result = mysql_query($sql,$lnk);
  56. if($query_result){
  57. echo '写入数据:';
  58. echo $csv_arr[$i]."数据写入成功。\n\r";
  59. }else{
  60. echo '写入数据失败';
  61. echo $csv_arr[$i]."数据写入失败!!!\n\r";
  62. }
  63. $i++;
  64. }
  65. mysql_close($lnk);
  66. unset($sql,$sql_list,$write_result,$csv_arr,$query_result,$lnk);
  67. ?>

人气教程排行