作爲替代到fgetcsv
和迭代,你也可以使用正則表達式來獲得相應的線路,例如對於
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.
使用
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);
和接收
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."
}
}
有沒有這個基準測試,雖然。根據CSV文件的大小,由於file_get_contents
將整個文件加載到變量中,這可能會佔用大量內存。
另一個替代與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";
}
}