2011-12-09 43 views
2

閱讀CSV行我有一個包含四個數據字段的CSV文件:如何通過線和輸出用PHP

date;place;time;event 

第一個是日期,你可以看到。

我需要逐行讀取CSV,將DATE與當前日期進行比較,並從當前日期的行開始輸出十行。

我試過這段代碼:

<?php 
date_default_timezone_set("Europe/Zagreb"); 
$today = date('Ymd'); 

$file_handle = fopen("data.csv", "r"); 

while (!feof($file_handle)) { 

$line_of_text = fgetcsv($file_handle, 1024,";"); 

if ($line_of_text[0] >= $today) echo $line_of_text[0] . "-" . $line_of_text[1]. "-" . $line_of_text[2] . "-" . $line_of_text[3] . "<BR>"; 
} 

fclose($file_handle);  
?> 

但我不能打破,經過10線。我在CSV和代碼中使用了YYYYMMDD日期格式,所以基本上我使用數字而不是日期。

回答

4

試試這個:

date_default_timezone_set("Europe/Zagreb"); 

$today = date('Ymd'); 

$file_handle = fopen("data.csv", "r"); 
$counter = 0; 
while (!feof($file_handle)) { 
    $line_of_text = fgetcsv($file_handle, 1024,";"); 
    if ($line_of_text[0] >= $today) { 
     echo $line_of_text[0] . "-" . $line_of_text[1]. "-" 
      . $line_of_text[2] . "-" . $line_of_text[3] . "<br />"; 
     $counter++; 
    } 
    if ($counter == 10) break; 
} 

fclose($file_handle); 
+0

它的工作原理,ty ...它只是需要: if($ counter == 10){break; } – user1089790

+0

這裏應該有'=='我從頭開始編寫時一定要小心:) – piotrekkr

1

如果條件應該加入的strtotime固定之前,你可以比較:

if (strtotime($line_of_text[0]) >= strtorime($today)) 

你糾正的一段代碼將是:

$counter = 0; 
while (!feof($file_handle)) { 
    $line_of_text = fgetcsv($file_handle, 1024,";"); 
    if (strtotime($line_of_text[0]) >= strtotime($today)) { 
     echo $line_of_text[0] . "-" . $line_of_text[1]. "-" . $line_of_text[2] 
      . "-" . $line_of_text[3] . "<BR>"; 
     $counter++; 
    } 
    if ($counter == 10) break; 
}