如何在php中获取目录中的最新文件

How to get the newest file in a directory in php(如何在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中获取目录中的最新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)