2

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.

2 Answers 2

4

Try this:

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);
Sign up to request clarification or add additional context in comments.

2 Comments

it works, ty... it just needs: if ($counter == 10) { break; }
right there should be == I must be more careful when writing from head :)
1

if condition should be fixed by adding strtotime before you can compare:

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

Your corrected piece of code will be:

$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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.