如何在PHP中获取指定目录最后修改的TXT文件内容并存储到变量
获取目录中最新修改的TXT文件内容
Got it, let's fix this step by step! Your current code has two main issues: first, scandir($Directory, 1) sorts files by filename in reverse order—not by their last modified time. Second, you're using a variable $filesInTestLog that you never defined (you named the scandir result $downloads).
Here's a complete, working solution to read the content of the most recently modified .txt file into a variable:
$Directory = './testlog'; // 1. 获取目录下所有文件,过滤出真正的.txt文件(排除目录和非txt文件) $txtFiles = array_filter(scandir($Directory), function($file) use ($Directory) { $fullPath = $Directory . DIRECTORY_SEPARATOR . $file; // 只保留文件(不是目录)且后缀为txt的项 return is_file($fullPath) && strtolower(pathinfo($fullPath, PATHINFO_EXTENSION)) === 'txt'; }); // 处理没有找到txt文件的情况 if (empty($txtFiles)) { die("Error: No .txt files found in the directory."); } // 2. 按文件最后修改时间排序,最新的排在最前面 usort($txtFiles, function($fileA, $fileB) use ($Directory) { $pathA = $Directory . DIRECTORY_SEPARATOR . $fileA; $pathB = $Directory . DIRECTORY_SEPARATOR . $fileB; // 用filemtime获取修改时间,倒序排列 return filemtime($pathB) - filemtime($pathA); }); // 3. 获取最新的那个文件的完整路径 $latestTxtFile = $Directory . DIRECTORY_SEPARATOR . reset($txtFiles); // 4. 读取文件内容到变量 $fileContent = file_get_contents($latestTxtFile); // 现在$fileContent就是你需要的最新txt文件内容,可以后续使用了
关键细节说明:
array_filter:确保我们只处理实际的.txt文件,排除掉.、..这些目录项,以及非txt格式的文件。usort+filemtime:这是核心——通过文件的最后修改时间来排序,保证我们拿到的是最新的文件,而不是按文件名排序的结果。file_get_contents:直接读取文件内容到变量,这就是你之前缺失的关键步骤。
内容的提问来源于stack exchange,提问作者Mustafa zamani
相关产品推荐
相关产品推荐

