Does not scan entire folders – extremely fast, in milliseconds!
You can use PHP's built-in `DirectoryIterator` to quickly retrieve the first.txt file within a specified directory.
The specific implementation method is as follows:
$dir = '/path/to/dir'; // 指定的文件夹路径
$iterator = new DirectoryIterator($dir); // 获取目录迭代器
foreach ($iterator as $fileinfo) { // 遍历目录
if (!$fileinfo->isDir() && $fileinfo->getExtension() === 'txt') { // 判断是否是txt文件
$txtfile = $fileinfo->getRealPath(); // 获取文件的绝对路径
break; // 找到第一个txt文件即退出循环
}
}In the above code, we first create a DirectoryIterator object, and then use a foreach loop to iterate over all files and subdirectories within that directory. During the iteration, we check whether the current file is a.txt file; if so, we retrieve its absolute path and store it in the $txtfile variable, and finally use the break statement to exit the loop. Since the DirectoryIterator only returns the filenames in the directory without actually opening the files, this approach is quite efficient.
Note that the above code will only retrieve the first.txt file in the directory; if you need to retrieve all.txt files, you should change the $txtfile variable to an array and return that array after iterating through the entire directory.