目前,MySQL數據庫用來存數據是非常不錯的,所以代碼爲:
<?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);
}
}
}