php 如何在php中获取目录中的最新文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11597421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the newest file in a directory in php
提问by Mike
So I have this app that processes CSV files. I have a line of code to load the file.
所以我有这个处理 CSV 文件的应用程序。我有一行代码来加载文件。
$myFile = "data/FrontlineSMS_Message_Export_20120721.csv"; //The name of the CSV file
$fh = fopen($myFile, 'r'); //Open the file
I would like to find a way in which I could look in the datadirectory 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.
我想找到一种方法,我可以看在data目录中,并获得最新的文件(它们都具有日期代码,以便它们将在内部顺序data),并设置名称等于$myFile。
I really couldn't find and understand the documentation of php directories so any helpful resources would be appreciated as well. Thank you.
我真的找不到和理解 php 目录的文档,所以任何有用的资源也将不胜感激。谢谢你。
回答by Matchu
Here's an attempt using scandir, assumingthe only files in the directory have timestamped filenames:
这是使用 的尝试scandir,假设目录中唯一的文件具有带时间戳的文件名:
$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.
我们首先按降序列出目录中的所有文件,然后,该列表中的第一个文件具有“最大”文件名——因此具有最大的时间戳值——因此是最新的。
Note that scandirwas added in PHP 5, but its documentation pageshows how to implement that behavior in PHP 4.
请注意,它scandir是在 PHP 5 中添加的,但其文档页面显示了如何在 PHP 4 中实现该行为。

