As an alternative to fgetcsv and iteration, you can also use regular expressions to get matching strings, for example. 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.
using
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 get
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." } }
Do not compare it. Depending on the size of your CSV file, this can lead to heavy memory due to file_get_contents loading the entire file into a variable.
Another alternative to 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"; } }
Gordon
source share