Reading CSV Rows with fgetcsv
Use PHP’s CSV parser so quoted commas and escaped values are handled correctly.
$handle = fopen($file["tmp_name"], "r");
if ($handle === false) {
exit("The uploaded file could not be read.");
}
$headers = fgetcsv($handle);
$expected = ["match_id", "team_name", "wins", "losses"];
if ($headers !== $expected) {
fclose($handle);
exit("The CSV headings do not match the expected format.");
}
$rowNumber = 1;
while (($row = fgetcsv($handle)) !== false) {
$rowNumber++;
// Validate and store this row.
}
fclose($handle);
This loop demonstrates iteration. The header comparison prevents values being assigned to the wrong fields.
Check
- File open failure is handled.
- The header is read separately.
- Exact expected headings are checked.
- Row numbers are tracked for useful feedback.
- The handle is closed.