Home  >  Q&A  >  body text

Translate PHP script to read CSV file and return echo multiple times

<p>I have written a PHP script that reads a CSV file and publishes the resulting radio schedule on a website based on time and date. However, it appears it will be released twice. <br /><br />The following is the script content:</p><p><br /></p> <pre class="brush:php;toolbar:false;"><?php // Step 1: Replace 'data.csv' with the path to your CSV file $csvFile = 'schedule.csv'; // Step 2: Read CSV and store its contents in an array if (($handle = fopen($csvFile, 'r')) !== false) { $csvData = []; while (($data = fgetcsv($handle)) !== false) { $csvData[] = $data; } fclose($handle); } else { die("Error opening CSV file."); } // Step 3: Get the current day and time $currentDay = date('l'); // l gives the full textual representation of the day (e.g., "Monday") $currentHour = date('H'); // H gives the hour in 24-hour format (e.g., "13" for 1 PM) // Adjust hour offset below. $Hour = $currentHour 1; // Step 4: Filter the array based on the current day and time $filteredData = []; foreach ($csvData as $row) { // Assuming that your CSV file has a "Day" column and a "Time" column $day = $row[0]; $time = intval($row[1]); $program_name= $row[2]; $program_when= $row[2]; $program_img= $row[4]; // Check if the row matches the current day and time if ($day === $currentDay && $Hour >= $time) { $filteredData[] = $row; } } // Step 5: Display the filtered data with CSS classes for each row if (count($filteredData) > 0) { foreach ($filteredData as $row) { echo "<div class='row'>"; echo "<div class='col-5'>"; echo "<img src='$row[4]' width='90' height='90' border='0'>"; echo "</div>"; echo "<div class='col-7'>"; echo "<h3>$row[2]<br>$row[3]</h3>"; echo "</div>"; echo "</div>"; } } else { echo 'Not available.'; }</pre> <p>This is the data I tested with in a CSV file: </p> <pre class="brush:php;toolbar:false;">Friday,12,MMV,until 1pm,top_mmv.png Friday,13,MMV,until 2pm,top_mmv.png Friday,14,MMV,until 3pm,top_mmv.png Friday,15,MMV,until 4pm,top_mmv.png</pre> <p>But when it gets to 2pm on Friday, it posts both the 1pm and 2pm rows. What did I do wrong? </p>
P粉127901279P粉127901279460 days ago582

reply all(1)I'll reply

  • P粉481815897

    P粉4818158972023-08-07 17:28:40

    You need to specify the conditions for collecting data,

    if ($day === $currentDay && $Hour >= $time) {
    

    For example, the current time now is 14 o'clock (add 1 hour is your adjustment).

    $Hour >= $time

    15 >= time from first line of csv is 12 - true
    15 >= time from second line of csv is 13 - true
    15 >= time from third line of csv is 14 - true
    15 >= 15 - true

    I think you can see where the problem is.

    reply
    0
  • Cancelreply