如何用php逐行读取CSV并输出
我有一个 CSV 文件,其中包含四个数据字段:
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 日期格式,所以基本上我使用的是数字,而不是日期。
I have a CSV file that contains four data fields:
date;place;time;event
First one is date, as you can see.
I need to read CSV line by line, compare DATE with current date and output ten lines starting from the line with current date.
I tried this code:
<?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);
?>
But I can't break that after 10 lines. I used YYYYMMDD date format in CSV and code so basically I work with numbers, not dates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
Try this:
if 条件应该通过在比较之前添加 strtotime 来修复:
您更正的代码段将是:
if condition should be fixed by adding strtotime before you can compare:
Your corrected piece of code will be: