2015-11-05 53 views
0

我想通過PHP連接到FTP服務器,並從某個目錄獲取最新文件並將其顯示在該PHP文件中。PHP:通過FTP打開並顯示來自文件夾的最新文件

所以我可以去www.domain.com/file.php看看那個文件裏有什麼。 這些文件具有以下名稱「Filename_20150721-085620_138.csv」,所以第二個值20150721是實際日期。 另外這些文件只包含CSV文本。

有什麼辦法可以達到這個目的嗎?

+0

http://php.net/manual/en/function.ftp-nlist.php –

回答

1

歡迎來到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保存的最新文件名。這是你以後的事嗎?

+0

在這種情況下,簡單的字符串比較($ tmp [1]')就可以完成這項工作。將字符串轉換爲時間是一種矯枉過正的行爲。無論如何+1 –