如何在php中获取目录中的最新文件
所以我有这个处理 CSV 文件的应用程序.我有一行代码来加载文件.
So I have this app that processes CSV files. I have a line of code to load the file.
$myFile = "data/FrontlineSMS_Message_Export_20120721.csv"; //The name of the CSV file
$fh = fopen($myFile, 'r'); //Open the file
我想找到一种方法来查看 data
目录并获取最新的文件(它们都有日期标签,因此它们在 data
) 并将名称设置为等于 $myFile
.
I would like to find a way in which I could look in the data
directory and get the newest file (they all have date tags so they would be in order inside of data
) and set the name equal to $myFile
.
我真的找不到和理解 php 目录的文档,所以任何有用的资源也将不胜感激.谢谢.
I really couldn't find and understand the documentation of php directories so any helpful resources would be appreciated as well. Thank you.
推荐答案
这是使用 scandir
的尝试,假设目录中仅有的文件具有带时间戳的文件名:
Here's an attempt using scandir
, assuming the only files in the directory have timestamped filenames:
$files = scandir('data', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];
我们首先按降序列出目录中的所有文件,然后,该列表中的第一个文件具有最大"文件名——因此具有最大的时间戳值——因此是最新的.
We first list all files in the directory in descending order, then, whichever one is first in that list has the "greatest" filename — and therefore the greatest timestamp value — and is therefore the newest.
请注意,scandir
是在 PHP 5 中添加的,但 其文档页面 显示了如何在 PHP 4 中实现该行为.
Note that scandir
was added in PHP 5, but its documentation page shows how to implement that behavior in PHP 4.
相关文章