开发者

PHP Read CSV and filter by date

开发者 https://www.devze.com 2022-12-17 04:33 出处:网络
I have the following CSV Date,Event,Description 24/01/2010,Football,Football practice for all Years. 开发者_StackOverflow24/01/2010,Cricket,Cricket Practice for all Years.

I have the following CSV

Date,Event,Description
24/01/2010,Football,Football practice for all Years.
开发者_StackOverflow24/01/2010,Cricket,Cricket Practice for all Years.
25/01/2010,Piano Lessons,Paino lessons for Year 10.

Date, Event and Description are the headers that I want to filter by.

I'm getting todays date and then I want to read the CSV and output the event/s that match todays date. I also want to get tomorrows events as well.


As mentioned above you do want to use fgetcsv(). Here's how you might do it (untested):

<?php
if (($handle = fopen("test.csv", "r")) !== FALSE) {
   $today = strtotime("today");
   $tomorrow = strtotime("tomorrow");
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if (strtotime($data[0]) == $today || strtotime($data[0]) == $tomorrow)) {
            echo 'Category: ' . $data[1] . "<br>\n";
            echo 'Event: ' . $data[0] . "<br><br>\n\n";
        }        
    }
    fclose($handle);
}
?>


The fastest (yet not optimal) way to do this is using fgetcsv and then iterate over the table, picking out those dates that are today.

I'd probably reconsider the format of the data (make it a database), unless there are other apps depending on it.


There are pretty much many ways to read a CSV files; you can also read in line by line and use the split function to separate each filed as an element in an array.

If search speed and complexity is not a concern, you can do a linear iteration and check for dates. You may want to use strtotime to convert the date into a unix timestamp for comparison.

If the search speed is important, then convert the date to timestamp, have an associative array which key is the timestamp (essentially a hash table)

To get tomorrow's date, check out the date function documentation in the PHP manual.


one way

$today=date('d/m/Y');
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
$tmr = date("d/m/Y", $tomorrow)."\n";
$handle = fopen("file", "r");
fgets($handle,2048);
while (($data = fgetcsv($handle, 2048, ",")) !== FALSE) {
    $date=explode("/",$data[0]);
    if ( $today == $data[0] || $tmr == $data[0]){
        $j = implode(",", $data);
        print $j."\n";
    }
}
fclose($handle);


As an alternative to fgetcsv and iterating, you could also use a Regular Expressions to get the appropriate lines, e.g. for

Date,Event,Description
24/01/2010,Football,Football practice for all Years.
24/01/2010,Cricket,Cricket Practice for all Years.
25/01/2010,Piano Lessons,Paino lessons for Year 10.
26/01/2010,Piano Lessons II.

use

date_default_timezone_set('Europe/Berlin');    
$pattern = sprintf('#%s.*|%s.*#', date('d/m/Y'), 
                                  date('d/m/Y', strtotime("+1 day")) );
$file = file_get_contents('filename.csv');
preg_match_all($pattern, $file, $matches);
var_dump($matches);

and receive

array(1) {
  [0]=>
  array(3) {
    [0]=> string(53) "24/01/2010,Football,Football practice for all Years."
    [1]=> string(51) "24/01/2010,Cricket,Cricket Practice for all Years."
    [2]=> string(52) "25/01/2010,Piano Lessons,Paino lessons for Year 10."
  }
}

Haven't benchmarked this though. Depending on the size of your CSV file, this could get memory intensive, due to file_get_contents loading the entire file into a variable.


Another alternative with SplFileObject:

$today    = date('d/m/Y');
$tomorrow = date('d/m/Y', strtotime("+1 day"));
$file = new SplFileObject("csvfile.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
    list($date, $event, $description) = $row;
    if($date === $today || $date === $tomorrow) {
        echo "Come visit us at $date for $description";
    }
}


You can spend lot of time trying to traverse each line in csv file, or can try something like that:

$command = sprintf("grep '%s' -Er %s", date('d/m/Y'), $this->db);
$result = `$command`;

This example really works and it is really fast!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号