当前位置:首页 > PHP教程 > php高级应用 > 列表

php读取txt文件并将数据插入到数据库

发布:smiling 来源: PHP粉丝网  添加日期:2021-07-10 15:38:19 浏览: 评论:0 

这篇文章主要介绍了php读取txt文件并将数据插入到数据库的方法和示例代码,小文件大家可以参考第一种,大文件导入的话请参考第二种。

今天测试一个功能,需要往数据库中插入一些原始数据,PM给了一个txt文件,如何快速的将这个txt文件的内容拆分为所要的数组,然后再插入到数据库中?

serial_number.txt的示例内容:

serial_number.txt:

  1. DM00001A11 0116, 
  2. SN00002A11 0116, 
  3. AB00003A11 0116, 
  4. PV00004A11 0116, 
  5. OC00005A11 0116, 
  6. IX00006A11 0116, 

创建数据表:

  1. create table serial_number( 
  2. id int primary key auto_increment not null, 
  3. serial_number varchar(50) not null 
  4. )ENGINE=InnoDB DEFAULT CHARSET=utf8; 

php代码如下:

  1. $conn = mysql_connect('127.0.0.1','root','') or die("Invalid query: " . mysql_error()); 
  2. mysql_select_db('test', $conn) or die("Invalid query: " . mysql_error()); 
  3.  
  4. $content = file_get_contents("serial_number.txt"); 
  5. $contents= explode(",",$content);//explode()函数以","为标识符进行拆分 
  6.  
  7. foreach ($contents as $k => $v)//遍历循环 
  8. { 
  9.   $id = $k; 
  10.   $serial_number = $v; 
  11.   mysql_query("insert into serial_number (`id`,`serial_number`) 
  12.       VALUES('$id','$serial_number')"); 
  13. } 

备注:方法有很多种,我这里是在拆分txt文件为数组后,然后遍历循环得到的数组,每循环一次,往数据库中插入一次。

再给大家分享一个支持大文件导入的。

  1. <?php 
  2. /** 
  3.  * $splitChar 字段分隔符 
  4.  * $file 数据文件文件名 
  5.  * $table 数据库表名 
  6.  * $conn 数据库连接 
  7.  * $fields 数据对应的列名 
  8.  * $insertType 插入操作类型,包括INSERT,REPLACE 
  9.  */ 
  10. function loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields=array(),$insertType='INSERT'){ 
  11.   if(emptyempty($fields)) $head = "{$insertType} INTO `{$table}` VALUES('"; 
  12.   else $head = "{$insertType} INTO `{$table}`(`".implode('`,`',$fields)."`) VALUES('";  //数据头 
  13.   $end = "')"; 
  14.   $sqldata = trim(file_get_contents($file)); 
  15.   if(preg_replace('/\s*/i','',$splitChar) == '') { 
  16.     $splitChar = '/(\w+)(\s+)/i'; 
  17.     $replace = "$1','"; 
  18.     $specialFunc = 'preg_replace'; 
  19.   }else { 
  20.     $splitChar = $splitChar; 
  21.     $replace = "','"; 
  22.     $specialFunc = 'str_replace'; 
  23.   } 
  24.   //处理数据体,二者顺序不可换,否则空格或Tab分隔符时出错 
  25.   $sqldata = preg_replace('/(\s*)(\n+)(\s*)/i','\'),(\'',$sqldata);  //替换换行 
  26.   $sqldata = $specialFunc($splitChar,$replace,$sqldata);        //替换分隔符 
  27.   $query = $head.$sqldata.$end;  //数据拼接 
  28.   if(mysql_query($query,$conn)) return array(true); 
  29.   else { 
  30.     return array(false,mysql_error($conn),mysql_errno($conn)); 
  31.   } 
  32. } 
  33.  
  34. //调用示例1 
  35. require 'db.php'; 
  36. $splitChar = '|';  //竖线 
  37. $file = 'sqldata1.txt'; 
  38. $fields = array('id','parentid','name'); 
  39. $table = 'cengji'; 
  40. $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields); 
  41. if (array_shift($result)){ 
  42.   echo 'Success!<br/>'; 
  43. }else { 
  44.   echo 'Failed!--Error:'.array_shift($result).'<br/>'; 
  45. } 
  46. /*sqlda ta1.txt 
  47. 1|0|A 
  48. 2|1|B 
  49. 3|1|C 
  50. 4|2|D 
  51.  
  52. -- cengji 
  53. CREATE TABLE `cengji` ( 
  54.  `id` int(11) NOT NULL AUTO_INCREMENT, 
  55.  `parentid` int(11) NOT NULL, 
  56.  `name` varchar(255) DEFAULT NULL, 
  57.  PRIMARY KEY (`id`), 
  58.  UNIQUE KEY `parentid_name_unique` (`parentid`,`name`) USING BTREE 
  59. ) ENGINE=InnoDB AUTO_INCREMENT=1602 DEFAULT CHARSET=utf8 
  60. */ 
  61.  
  62. //调用示例2 
  63. require 'db.php'; 
  64. $splitChar = ' ';  //空格 
  65. $file = 'sqldata2.txt'; 
  66. $fields = array('id','make','model','year'); 
  67. $table = 'cars'; 
  68. $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields); 
  69. if (array_shift($result)){ 
  70.   echo 'Success!<br/>'; 
  71. }else { 
  72.   echo 'Failed!--Error:'.array_shift($result).'<br/>'; 
  73. } 
  74. /* sqldata2.txt 
  75. 11 Aston DB19 2009 
  76. 12 Aston DB29 2009 
  77. 13 Aston DB39 2009 
  78.  
  79. -- cars 
  80. CREATE TABLE `cars` ( 
  81.  `id` int(11) NOT NULL AUTO_INCREMENT, 
  82.  `make` varchar(16) NOT NULL, 
  83.  `model` varchar(16) DEFAULT NULL, 
  84.  `year` varchar(16) DEFAULT NULL, 
  85.  PRIMARY KEY (`id`) 
  86. ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 
  87. */ 
  88.  
  89. //调用示例3 
  90. require 'db.php'; 
  91. $splitChar = '  ';  //Tab 
  92. $file = 'sqldata3.txt'; 
  93. $fields = array('id','make','model','year'); 
  94. $table = 'cars'; 
  95. $insertType = 'REPLACE'; 
  96. $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields,$insertType); 
  97. if (array_shift($result)){ 
  98.   echo 'Success!<br/>'; 
  99. }else { 
  100.   echo 'Failed!--Error:'.array_shift($result).'<br/>'; 
  101. } 
  102. /* sqldata3.txt 
  103. 11  Aston  DB19  2009 
  104. 12  Aston  DB29  2009 
  105. 13  Aston  DB39  2009  
  106. */ 
  107.  
  108. //调用示例3 
  109. require 'db.php'; 
  110. $splitChar = '  ';  //Tab 
  111. $file = 'sqldata3.txt'; 
  112. $fields = array('id','value'); 
  113. $table = 'notExist';  //不存在表 
  114. $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields); 
  115. if (array_shift($result)){ 
  116.   echo 'Success!<br/>'; 
  117. }else { 
  118.   echo 'Failed!--Error:'.array_shift($result).'<br/>'; 
  119. } 
  120.  
  121. //附:db.php 
  122. /*  //注释这一行可全部释放 
  123. ?> 
  124. <?php 
  125. static $connect = null; 
  126. static $table = 'jilian'; 
  127. if(!isset($connect)) { 
  128.   $connect = mysql_connect("localhost","root",""); 
  129.   if(!$connect) { 
  130.     $connect = mysql_connect("localhost","Zjmainstay",""); 
  131.   } 
  132.   if(!$connect) { 
  133.     die('Can not connect to database.Fatal error handle by /test/db.php'); 
  134.   } 
  135.   mysql_select_db("test",$connect); 
  136.   mysql_query("SET NAMES utf8",$connect); 
  137.   $conn = &$connect; 
  138.   $db = &$connect; 
  139. } 
  140. ?> 

-- 数据表结构:

  1. -- 100000_insert,1000000_insert 
  2.  
  3. CREATE TABLE `100000_insert` ( 
  4.  `id` int(11) NOT NULL AUTO_INCREMENT, 
  5.  `parentid` int(11) NOT NULL, 
  6.  `name` varchar(255) DEFAULT NULL, 
  7.  PRIMARY KEY (`id`) 
  8. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 
  9.  100000 (10万)行插入:Insert 100000_line_data use 2.5534288883209 seconds 

1000000(100万)行插入:Insert 1000000_line_data use 19.677318811417 seconds

可能报错:MySQL server has gone away

解决:修改my.ini/my.cnf   max_allowed_packet=20M

Tags: php读取txt文件

分享到: