您好,登錄后才能下訂單哦!
這篇文章主要講解了“php怎么讀取txt文件并將數(shù)據(jù)插入到數(shù)據(jù)庫(kù)”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“php怎么讀取txt文件并將數(shù)據(jù)插入到數(shù)據(jù)庫(kù)”吧!
今天測(cè)試一個(gè)功能,需要往數(shù)據(jù)庫(kù)中插入一些原始數(shù)據(jù),PM給了一個(gè)txt文件,如何快速的將這個(gè)txt文件的內(nèi)容拆分為所要的數(shù)組,然后再插入到數(shù)據(jù)庫(kù)中?
serial_number.txt的示例內(nèi)容:
serial_number.txt:
DM00001A11 0116, SN00002A11 0116, AB00003A11 0116, PV00004A11 0116, OC00005A11 0116, IX00006A11 0116,
創(chuàng)建數(shù)據(jù)表:
create table serial_number( id int primary key auto_increment not null, serial_number varchar(50) not null )ENGINE=InnoDB DEFAULT CHARSET=utf8;
php代碼如下:
$conn = mysql_connect('127.0.0.1','root','') or die("Invalid query: " . mysql_error()); mysql_select_db('test', $conn) or die("Invalid query: " . mysql_error()); $content = file_get_contents("serial_number.txt"); $contents= explode(",",$content);//explode()函數(shù)以","為標(biāo)識(shí)符進(jìn)行拆分 foreach ($contents as $k => $v)//遍歷循環(huán) { $id = $k; $serial_number = $v; mysql_query("insert into serial_number (`id`,`serial_number`) VALUES('$id','$serial_number')"); }
備注:方法有很多種,我這里是在拆分txt文件為數(shù)組后,然后遍歷循環(huán)得到的數(shù)組,每循環(huán)一次,往數(shù)據(jù)庫(kù)中插入一次。
再給大家分享一個(gè)支持大文件導(dǎo)入的
<?php /** * $splitChar 字段分隔符 * $file 數(shù)據(jù)文件文件名 * $table 數(shù)據(jù)庫(kù)表名 * $conn 數(shù)據(jù)庫(kù)連接 * $fields 數(shù)據(jù)對(duì)應(yīng)的列名 * $insertType 插入操作類型,包括INSERT,REPLACE */ function loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields=array(),$insertType='INSERT'){ if(empty($fields)) $head = "{$insertType} INTO `{$table}` VALUES('"; else $head = "{$insertType} INTO `{$table}`(`".implode('`,`',$fields)."`) VALUES('"; //數(shù)據(jù)頭 $end = "')"; $sqldata = trim(file_get_contents($file)); if(preg_replace('/\s*/i','',$splitChar) == '') { $splitChar = '/(\w+)(\s+)/i'; $replace = "$1','"; $specialFunc = 'preg_replace'; }else { $splitChar = $splitChar; $replace = "','"; $specialFunc = 'str_replace'; } //處理數(shù)據(jù)體,二者順序不可換,否則空格或Tab分隔符時(shí)出錯(cuò) $sqldata = preg_replace('/(\s*)(\n+)(\s*)/i','\'),(\'',$sqldata); //替換換行 $sqldata = $specialFunc($splitChar,$replace,$sqldata); //替換分隔符 $query = $head.$sqldata.$end; //數(shù)據(jù)拼接 if(mysql_query($query,$conn)) return array(true); else { return array(false,mysql_error($conn),mysql_errno($conn)); } } //調(diào)用示例1 require 'db.php'; $splitChar = '|'; //豎線 $file = 'sqldata1.txt'; $fields = array('id','parentid','name'); $table = 'cengji'; $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields); if (array_shift($result)){ echo 'Success!<br/>'; }else { echo 'Failed!--Error:'.array_shift($result).'<br/>'; } /*sqlda ta1.txt 1|0|A 2|1|B 3|1|C 4|2|D -- cengji CREATE TABLE `cengji` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parentid` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `parentid_name_unique` (`parentid`,`name`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=1602 DEFAULT CHARSET=utf8 */ //調(diào)用示例2 require 'db.php'; $splitChar = ' '; //空格 $file = 'sqldata2.txt'; $fields = array('id','make','model','year'); $table = 'cars'; $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields); if (array_shift($result)){ echo 'Success!<br/>'; }else { echo 'Failed!--Error:'.array_shift($result).'<br/>'; } /* sqldata2.txt 11 Aston DB19 2009 12 Aston DB29 2009 13 Aston DB39 2009 -- cars CREATE TABLE `cars` ( `id` int(11) NOT NULL AUTO_INCREMENT, `make` varchar(16) NOT NULL, `model` varchar(16) DEFAULT NULL, `year` varchar(16) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 */ //調(diào)用示例3 require 'db.php'; $splitChar = ' '; //Tab $file = 'sqldata3.txt'; $fields = array('id','make','model','year'); $table = 'cars'; $insertType = 'REPLACE'; $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields,$insertType); if (array_shift($result)){ echo 'Success!<br/>'; }else { echo 'Failed!--Error:'.array_shift($result).'<br/>'; } /* sqldata3.txt 11 Aston DB19 2009 12 Aston DB29 2009 13 Aston DB39 2009 */ //調(diào)用示例3 require 'db.php'; $splitChar = ' '; //Tab $file = 'sqldata3.txt'; $fields = array('id','value'); $table = 'notExist'; //不存在表 $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields); if (array_shift($result)){ echo 'Success!<br/>'; }else { echo 'Failed!--Error:'.array_shift($result).'<br/>'; } //附:db.php /* //注釋這一行可全部釋放 ?> <?php static $connect = null; static $table = 'jilian'; if(!isset($connect)) { $connect = mysql_connect("localhost","root",""); if(!$connect) { $connect = mysql_connect("localhost","Zjmainstay",""); } if(!$connect) { die('Can not connect to database.Fatal error handle by /test/db.php'); } mysql_select_db("test",$connect); mysql_query("SET NAMES utf8",$connect); $conn = &$connect; $db = &$connect; } ?>
//*/
復(fù)制代碼
-- 數(shù)據(jù)表結(jié)構(gòu):
-- 100000_insert,1000000_insert
CREATE TABLE `100000_insert` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parentid` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
100000 (10萬(wàn))行插入:Insert 100000_line_data use 2.5534288883209 seconds
1000000(100萬(wàn))行插入:Insert 1000000_line_data use 19.677318811417 seconds
//可能報(bào)錯(cuò):MySQL server has gone away
//解決:修改my.ini/my.cnf max_allowed_packet=20M
感謝各位的閱讀,以上就是“php怎么讀取txt文件并將數(shù)據(jù)插入到數(shù)據(jù)庫(kù)”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)php怎么讀取txt文件并將數(shù)據(jù)插入到數(shù)據(jù)庫(kù)這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。