Hongmu Notes
Home Language Notes Use PHP to batch-import millions of TXT files into a database.
Language Notes PHP

Use PHP to batch-import millions of TXT files into a database.

Use PHP to batch-import millions of TXT files into a database.

Currently, the MySQL database is an excellent choice for storing data; therefore, the code is as follows:

<?php
// 调用函数
// moveFilesByExtension('./回收站', './句子采集', '.txt');die;

// 数据库连接信息
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("数据库连接失败: " . $conn->connect_error);
}

// 设置每次读取的文件数量
$fileLimit = 100;

// 打开文件夹
$folderPath = './句子采集/';  // 替换为实际的文件夹路径
if ($dh = opendir($folderPath)) {
    $fileCount = 0;  // 计算已读取的文件数量
    while (($file = readdir($dh)) !== false) {
        if ($file != '.' && $file != '..' && pathinfo($file, PATHINFO_EXTENSION) == 'txt') {
            $filePath = $folderPath . $file;
            $content = file_get_contents($filePath);
            $title = basename($filePath);
           // 将文件内容插入数据库表
            $sql = "INSERT INTO caiji_juzi (title, content) VALUES ('" . $conn->real_escape_string($title) . "', '" . $conn->real_escape_string($content) . "')";   // 根据你的表结构修改表名和字段名
            if ($conn->query($sql) === TRUE) {
                if (rename($filePath, str_replace('句子采集', '回收站', $filePath))) {
                    echo "文件 " . $file . " 插入成功并移动到回收站<br>";
                    echo '<meta http-equiv="refresh" content="1">';
                } else {
                    echo "文件 " . $file . " 插入成功但移动失败<br>";
                }
            } else {
                echo "文件 " . $file . " 插入失败: " . $conn->error . "<br>";
            }

            $fileCount++;

            // 如果已读取的文件数量达到设定的限制,停止读取
            if ($fileCount >= $fileLimit) {
                break;
            }
        }
    }
    closedir($dh);
}

// 关闭数据库连接
$conn->close();

function moveFilesByExtension($sourceDir, $targetDir, $fileExtension) {
    if (!is_dir($sourceDir) || !is_dir($targetDir)) {
        echo '源文件夹或目标文件夹不存在';
    } else {
        if ($dh = opendir($sourceDir)) {
            while (($file = readdir($dh)) !== false) {
                if (substr($file, -strlen($fileExtension)) === $fileExtension) {
                    rename("$sourceDir/$file", "$targetDir/$file");
                }
            }
            closedir($dh);
        }
    }
}

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

Responsive Youth Growth Training Camp Training Website Template 0184

Responsive Youth Growth Training Camp Training Website Template 0184 Practical Collection Yiyou template

An eYouCMS responsive website template designed specifically for youth development camps and the training industry. Its vibrant educational design effectively showcases camp curricula, camp environments, faculty expertise, and student growth success stories, helping quality education institutions attract parents and young participants online. Template Demo | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Common Installation Questions for eYouCMS...
👁 53
(PC + WAP) Eco-friendly equipment – pbootCMS corporate website template; Download the eco-friendly corporate website source code – 0088

(PC + WAP) Eco-friendly equipment – pbootCMS corporate website template; Download the eco-friendly corporate website source code – 0088 Practical Collection pbootcms Template

This PbootCMS template is a green-themed corporate website designed specifically for environmental protection equipment manufacturers, supporting both desktop and mobile devices. Its fresh and natural design effectively showcases environmental protection equipment products – such as wastewater treatment systems and air purification solutions – helping environmental protection companies establish a professional online presence and expand their business collaboration channels. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password:...
👁 46
Elderly Wellness and Fitness Association Website Template 0844

Elderly Wellness and Fitness Association Website Template 0844 Practical Collection Yiyou template

An EyouCMS website template designed specifically for senior care and fitness associations. Its warm, health-focused design effectively showcases senior care services, fitness activities, association functions, and member profiles. This template helps senior care institutions attract elderly individuals and their family members online. Template Preview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (Ey...
👁 39
(Adaptive mobile version) PBootCMS template for excavator and construction machinery websites; Download source code for bulldozer and excavator equipment websites – 0720

(Adaptive mobile version) PBootCMS template for excavator and construction machinery websites; Download source code for bulldozer and excavator equipment websites – 0720 Practical Collection pbootcms Template

A PbootCMS website template for excavators and bulldozers – compatible with both PC and WAP devices. The design features a bold yellow color scheme, ideal for showcasing large-scale construction machinery such as excavators and bulldozers. This template helps construction machinery companies showcase their products online and attract clients in the infrastructure and mining sectors. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5....
👁 51
Responsive automotive engine parts website template 0185

Responsive automotive engine parts website template 0185 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the automotive engine and accessories industry. Its professional automotive design style enables effective display of engine products, automotive parts, technical specifications, and maintenance services. It helps automotive parts enterprises showcase their products online and attract customers from the automotive aftermarket. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | Eyou...
👁 30
(PC + WAP) Eco-friendly equipment – pbootCMS website template; Download source code for a resource recycling and new energy website – 0089

(PC + WAP) Eco-friendly equipment – pbootCMS website template; Download source code for a resource recycling and new energy website – 0089 Practical Collection pbootcms Template

A PbootCMS eco-friendly equipment website template designed for the resource recycling and new energy industries, compatible with both PC and WAP devices. Its clean, minimalist design effectively showcases waste material disposal solutions and new energy technologies. This template helps renewable resource or new energy enterprises demonstrate their corporate strength online and seize additional partnership opportunities. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin
👁 46