View Full Version : Reading Most Recent CSV File in Directory

02-19-2010, 12:27 AM
I thought I had wrapped this project up, but found out that the program I use to FTP a csv file to my website is best used in time stamp mode.

That is, each day a newly named csv file is uploaded with that days data.

I currently have this script that I use to display the data on my website:

echo "<table align='left' width='685' bordercolor='ccc' border='1'>";
echo "<tr><td><strong>Date</strong></td><td><strong>MPSAS</strong></td><td><strong>NELM</strong></td><td><strong>Temp (C)</strong></td></td>";
$file = "myfile.csv";
for ($i = count($content) - 1; $i >=1 ; $i--) {
$row = explode(",", $content[$i]);
echo "<tr><td>{$row[0]}</td><td>{$row[1]}</td><td>{$row[2]}</td><td>{$row[7]}</td></td>";}echo "</table>";

To read the most recent file I know I need to list the dir contents, sort, and then select the newest file, but I need some help getting started.

Anyone have experience with that is willing to help me out?


02-19-2010, 10:30 AM
Check out the readdir manual page for the basic code for opening, reading and outputting directory contents:


to do the sort, load the filenames into an array instead of printing them immediately, then sort the array and output from it e.g. (untested)

if ($handle = opendir('/path/to/files')) {
$arrFiles = array();
while (false !== ($file = readdir($handle))) {
$arrFiles[] = $file;

This assumes that the file name will self-sort into correct order. If not you may need to customise the sort using usort() or similar.



02-19-2010, 10:45 AM
My 5 cents (does not address the question but only the code posted): The method you are using for reading and parsing a CSV file does not take into account several rules which the CSV format implies (http://en.wikipedia.org/wiki/Comma-separated_values#Basic_Rules). Also on big files (if you ever have some) file() could be quite memory consuming. I would advise to look at the Manual entry for fgetcsv() (http://us.php.net/fgetcsv) and use this function for reading/parsing a CSV file. It should be much more CSV-format complaint than the method used by you currently.

02-20-2010, 06:46 AM
Sort files by last modified time in descending order:

$files = glob( './files/*.csv' );

array_map( 'filemtime', $files ),

The first file in the array will be the newest, and so on down the list to the last one being the oldest.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum