首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 讀取 TXT 文件生成 SQL 並批量插入數據庫的完整實現代碼

     編輯:PHP 綜合知識

前言

在實際開發中,經常需要將文本文件中的數據批量導入數據庫。本文分享一個原創的 PHP 函數 loadTxtDataIntoDatabase,它能自動讀取 TXT 文件,根據指定分隔符解析字段,動態構建 SQL 語句並執行批量插入或替換操作,支持 INSERT 和 REPLACE 兩種模式,並能自動處理空格、制表符、竄線等多種分隔符。

核心函數實現

<?php
/**
 * 將 TXT 文件數據批量導入數據庫
 * @param string $splitChar 字段分隔符(如 '|', ' ', '\t' 等)
 * @param string $file 數據文件路徑
 * @param string $table 目標數據表名
 * @param resource $conn MySQL 連接資源
 * @param array $fields 對應的列名數組,為空則不指定列名
 * @param string $insertType 操作類型:'INSERT' 或 'REPLACE'
 * @return array 執行結果 [成功布爾值, 錯誤信息, 錯誤代碼]
 */
function loadTxtDataIntoDatabase($splitChar, $file, $table, $conn, $fields = array(), $insertType = 'INSERT') {
    // 構建 SQL 前綴
    if (empty($fields)) {
        $head = "{$insertType} INTO `{$table}` VALUES('";
    } else {
        $head = "{$insertType} INTO `{$table}`(`" . implode('`,`', $fields) . "`) VALUES('";
    }
    $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';
    }

    // 處理換行符:將換行替換為 '),('
    // 注意順序:先處理換行,再處理分隔符,否則空格/Tab 分隔時會出錯
    $sqldata = preg_replace('/(\s*)(\n+)(\s*)/i', '\'),(\'', $sqldata);
    // 處理字段分隔符
    $sqldata = $specialFunc($splitChar, $replace, $sqldata);

    // 拼接完整 SQL
    $query = $head . $sqldata . $end;

    // 執行查詢並返回結果
    if (mysql_query($query, $conn)) {
        return array(true);
    } else {
        return array(false, mysql_error($conn), mysql_errno($conn));
    }
}

使用示例

示例 1:竄線分隔符,指定字段

<?php
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/>';
}

數據文件 sqldata1.txt 內容:

|0|A
|1|B
|1|C
|2|D

對應表結構:

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 DEFAULT CHARSET=utf8;

示例 2:空格分隔符

<?php
require 'db.php';
$splitChar = ' ';
$file = 'sqldata2.txt';
$fields = array('id', 'make', 'model', 'year');
$table = 'cars';
$result = loadTxtDataIntoDatabase($splitChar, $file, $table, $conn, $fields);
// 結果判斷同上...

數據文件 sqldata2.txt:

Aston DB19 2009
Aston DB29 2009
Aston DB39 2009

示例 3:使用 REPLACE 模式

<?php
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);

性能測試數據

  • 10 萬行插入:約 2.55 秒
  • 100 萬行插入:約 19.68 秒

注意:大量數據插入時可能遇到 MySQL server has gone away 錯誤,解決方法是修改 my.ini/my.cnf 中的 max_allowed_packet=20M。

附:數據庫連接文件 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;
}

本代碼由 Zjmainstay 原創分享,適合快速導入結構化文本數據到 MySQL 數據庫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved