0

我有一个包含大约 10.000 个文本文件的文件夹。我想将这些文件导入到具有两列的 MySQL 表中。对于每一行,我希望文本文件的标题(例如 1234.txt)在一列中,文件的内容在另一列中。我可以使用 PHP。你会如何建议我这样做?

4

2 回答 2

1

您可以尝试以下操作,下面的代码将遍历目录中的所有文本文件,并将每个文件的文件名作为标题和内容作为内容添加到 MySQL 数据库。

<?php
$size = "";
//Change "MyFolder" with the path and name of the directory where the .txt files are located.
$dir = "MyFolder";

if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if($file == '.' || $file == '..') continue;

        $myFile = "$dir/$file";
        $fh = fopen($myFile, 'r');

        $size = filesize($myFile);
        if ($size > 0) {
        $content = fread($fh, $size);

        $title = $file; 
        echo $title."</br>";
        }

        $con=mysqli_connect("HostName","Username","Password","Database");
        // Check connection
        if (mysqli_connect_errno())
        {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }     
        mysqli_query($con,"INSERT INTO table_name (Title, Content) VALUES ('$title', '$content')");

        mysqli_close($con);  

        fclose($fh);
    }
closedir($handle);
}
?>
于 2013-08-19T16:54:51.007 回答
0

您可以(ab)使用LOAD DATA INFILE在列中加载整个文件。“技巧”只是提供文件中不存在的字符序列作为行/字段终止:

mysql> create table tbl(fname CHAR(255), data TEXT);
Query OK, 0 rows affected (0.35 sec)


mysql> LOAD DATA INFILE '/tmp/demo.txt' INTO TABLE tbl 
            FIELDS TERMINATED BY 'XXX' LINES TERMINATED BY 'YYY' 
            (data) SET fname = 'demo.csv';
Query OK, 1 row affected (0.00 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> select * from tbl;
+----------+--------------------------------------------------------------------------------------------------+
| fname    | data                                                                                             |
+----------+--------------------------------------------------------------------------------------------------+
| demo.csv | Date, Amount, Name
2013-01-01, 1000, "Apple"
2013-01-02, 500, "Orange"
2013-01-03, 250, "Prune"
 |
+----------+--------------------------------------------------------------------------------------------------+
1 rows in set (0.00 sec)

如果要加载文件夹中的所有文件,您必须使用宿主语言从循环中调用该语句您甚至可以使用简单的 shell 脚本来执行此操作:

for i in *.txt; do 
  echo "LOAD DATA INFILE '$i' INTO TABLE tbl 
                FIELDS TERMINATED BY 'XXX' LINES TERMINATED BY 'YYY' 
                (data) SET fname = '$i';";
  done
  | mysql -p -u user_name -h host_name db_name
于 2013-08-19T17:10:45.773 回答