【发布时间】:2015-11-05 20:17:45
【问题描述】:
我想通过 PHP 连接到 FTP 服务器,并从某个目录中获取最新的文件并在该 PHP 文件中显示它。
所以我可以转到www.domain.com/file.php 并查看该文件中的内容。
这些文件具有以下名称“Filename_20150721-085620_138.csv”,因此第二个值20150721 是实际日期。
这些文件也只包含 CSV 文本。
有什么办法可以做到吗?
【问题讨论】:
我想通过 PHP 连接到 FTP 服务器,并从某个目录中获取最新的文件并在该 PHP 文件中显示它。
所以我可以转到www.domain.com/file.php 并查看该文件中的内容。
这些文件具有以下名称“Filename_20150721-085620_138.csv”,因此第二个值20150721 是实际日期。
这些文件也只包含 CSV 文本。
有什么办法可以做到吗?
【问题讨论】:
欢迎来到 Stackoverflow! 考虑以下代码和解释:
// connect
$conn = ftp_connect('ftp.addr.com');
ftp_login($conn, 'user', 'pass');
// get list of files on given path
$files = ftp_nlist($conn, '');
$newestfile = null;
$time = 0;
foreach ($files as $file) {
$tmp = explode("_", $file); // Filename_20150721-085620_138.csv => $tmp[1] has the date in question
$year = substr($tmp[1], 0, 4); // 2015
$month = substr($tmp[1], 4, 2); // 07
$day = substr($tmp[1], 6, 2); // 21
$current = strtotime("$month/$day/$year"); // makes a timestamp from a string
if ($current >= $time) { // that is newer
$time = $current;
$newestfile = $file;
}
}
ftp_close($conn);
之后,您的 $newestfile 会保存最新的文件名。这就是你所追求的吗?
【讨论】:
$tmp[1])就可以完成这项工作。将字符串转换为时间是多余的。无论如何+1