How can PHP be used to parse a CSV file and output a table by day?
To parse a CSV file and output a table by day using PHP, you can read the CSV file line by line, extract the date from each row, group the data by day, and then output it in a table format with each day as a row.
<?php
// Open the CSV file
$csvFile = fopen('data.csv', 'r');
// Initialize an array to store data grouped by day
$dataByDay = [];
// Read the CSV file line by line
while (($row = fgetcsv($csvFile)) !== false) {
// Extract the date from the row
$date = date('Y-m-d', strtotime($row[0]));
// Group data by day
$dataByDay[$date][] = $row;
}
// Output the data in a table format
echo '<table>';
foreach ($dataByDay as $day => $data) {
echo '<tr><th colspan="2">' . $day . '</th></tr>';
foreach ($data as $row) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
}
echo '</table>';
// Close the CSV file
fclose($csvFile);
?>
Related questions
-
undefined variable PHP scripts mistakes
-
mysqli fetch array
-
concatenation strings PHP