-1

所以我有这个设备,它创建一个 CSV 文件并每 15 分钟更新一次文件中的数据,然后每天向我们的服务器发送一个新的 csv 文件。所以我想在一个网站上显示最新的数据。

我有一行代码可以使用 fgetcsv 加载文件,但是这段代码会打开特定文件夹中的特定 csv 文件。

$f_pointer=fopen("database/student01.csv","r"); // file pointer
$ar=fgetcsv($f_pointer);
print_r($ar);

我想找到一种方法来打开最新的 csv 文件和数组中的数据,以便我可以根据特定数据制作表格。

我是网络开发的新手,任何有用的资源将不胜感激。谢谢你。


更新

我找到了一种在目录中打开最新文件的方法

function pre_r($array) {
  echo '<pre>';
  print_r($array);
  echo '</pre>';
}

$files = scandir('database/AWLR/2018/10', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];

pre_r($newest_file); //file name

//to open file in array
$f_pointer=fopen("database/AWLR/2018/10/$newest_file","r"); // file pointer
$ar=fgetcsv($f_pointer);
pre_r($ar);

但是这段代码打开了 csv 文件的第一行,而我想打开最后一行(因为它是给出的最新数据)。有没有办法自动更改目录?因为这个代码必须每个月保持更新


最新更新

此代码有效,不幸的是它显示了 csv 文件的第一行,

$current_year = date('Y'); 
$current_month = date('m');
$files = scandir("database/AWLR/".$current_year."/".$current_month, 1); // use 0 for ascending order, and 1 for descending order
$newest_file = $files[0];

pre_r($newest_file); //file name

//to open file in array
$f_pointer=fopen("database/AWLR/".$current_year."/".$current_month."/".$newest_file,'r'); // file pointer
$ar=fgetcsv($f_pointer);
pre_r($ar);

有没有办法显示csv文件的最后一行?

这是我正在谈论的 csv 文件之一

.csv 文件

我已经解决了问题,谢谢大家

4

2 回答 2

1

这是您可以使用和测试的建议代码

$current_year = date('Y'); 
$current_month = date('m');
$files = scandir("database/AWLR/".$current_year."/".$current_month, 1); // use 0 for ascending order, and 1 for descending order
$newest_file = $files[0];

pre_r($newest_file); //file name

//to open file in array
$f_pointer=fopen("database/AWLR/".$current_year."/".$current_month."/".$newest_file,'r'); // file pointer
$ar=fgetcsv($f_pointer);
pre_r($ar);
于 2019-03-24T09:02:11.163 回答
0
    //this is your file path
    $files_location = "database/";

    //this function will return latest file in folder 
    function latest_file_Name ($files_location) {
    //open folder and reads whats inside
    $openDir = opendir($files_location);
    //look for each file in the folder. 
    while (false !== ($fileName = readdir($openDir))) {
    //ignore the  . and .. these are system folders. you can also ignore any other file if not necesery
    // for Example if($fileName != "." && $fileName != ".." && $fileName != "unwanted_file_name.csv)" in condition 
    if($fileName != "." && $fileName != "..")
    {
    $list[date("YmdHis ", filemtime($files_location.$fileName))]=$fileName; 
    }
    }
    rsort($list);
    $last_file =array_shift(array_values($list));
    return $last_file;
    }

    $last_file_in_folder = latest_file_Name($files_location);
    $f_pointer=fopen("database/".$last_file_in_folder,"r"); // file pointer
    $ar=fgetcsv($f_pointer);
    print_r($ar);

试试这个,我希望它能解决你的问题。

于 2019-03-24T09:10:03.173 回答