How to get the newest file in a directory in php(如何在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.
这篇关于如何在php中获取目录中的最新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在php中获取目录中的最新文件
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
