鍍金池/ 問答/PHP/ 通過php寫個API將txt文件中的數(shù)據(jù)寫入到數(shù)據(jù)庫中

通過php寫個API將txt文件中的數(shù)據(jù)寫入到數(shù)據(jù)庫中

現(xiàn)在項目需要寫個API將txt文件中的數(shù)據(jù)寫入到數(shù)據(jù)庫中。txt文件格式如下
1 測試數(shù)據(jù)一 English
2 測試數(shù)據(jù)二 chinese
3 測試數(shù)據(jù)三 American

現(xiàn)在通過下面代碼修改后插入
$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);

foreach ($contents as $k => $v)
{
$id = $k;
$serial_number = $v;
mysql_query("insert into serial_number (id,serial_number)

  VALUES('$id','$serial_number')");

}
插入數(shù)據(jù)量較小的時候沒什么問題,但是如果現(xiàn)在有30萬的數(shù)據(jù)似乎這樣不是很好,想請假一下大家有沒有更好些的辦法

回答
編輯回答
撥弦

LOAD DATA / mysqlimport
或者PHP更改讀取方式 yield

2018年8月5日 06:45
編輯回答
默念

只需要改變文件讀取方式就可以了, 不要用 file_get_contents() 方法, 那會把整個文件一次性讀入內(nèi)存. 改為逐行讀取就可以了:

<?php
$handle = @fopen("serial_number.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $contents = explode(",",$line);
        // 在這里把數(shù)據(jù)插入 mysql.
    }

    fclose($handle);
} else {
    // error opening the file.
} 
?>

如果想進一步優(yōu)化, 有幾個方向可以考慮:

  • 解析多行數(shù)據(jù), 一次性插入 mysql, 比如每次插入 50 條數(shù)據(jù).
  • 因為 php 模型簡單, 不支持多線程. 所以如果對時間要求高, 可以多起幾個進程, 分段讀取文件. 一般我做這類需求, 會首先考慮 python, 因此確實沒用過 php 讀取特定行. 翻了下文檔, 可參考 SplFileObject 這個類, 具體請自行研究下.
參考:
官方文檔 - file_get_contents()
官方文檔 - fgets()
官方文檔 - SplFileObject
2017年11月9日 22:09
編輯回答
疚幼

可以用 MySQL 的 LOAD DATA 指令導(dǎo)入數(shù)據(jù),速度比INSERT快很多

http://www.runoob.com/mysql/m...

2018年5月3日 23:04