BIT301 ยท 2082 ยท 5 marks
Write a program to parse a CSV file and display the content in the file.
Write a program to parse a CSV file and display the content in the file. [5]
Quick answer
A CSV file stores a table as plain text: one record per line, with the fields of a record separated by commas and any field that itself contains a comma or a quote wrapped in double quotes. Because of that quoting rule a CSV line cannot be split reliably by hand, so PHP supplies fgetcsv(), which reads one record from an open file and returns its fields as an array with the quoting already resolved.
Reading a CSV file and displaying its contents
Take the file data.csv:
Name,Age,City
Alice,23,Kathmandu
Bob,25,Pokhara
Charlie,22,Lalitpur
The script reads the first record as the list of column names, pairs each later record with those names using array_combine(), and prints the result.
<?php
$filename = "data.csv";
if (!is_readable($filename)) {
exit("The CSV file could not be read.");
}
$handle = fopen($filename, "r");
if ($handle === false) {
exit("Unable to open the CSV file.");
}
$header = fgetcsv($handle, 0, ",");
if ($header === false) {
fclose($handle);
exit("The CSV file is empty.");
}
echo "<table border='1'><tr>";
foreach ($header as $column) {
// file contents are untrusted, so they are escaped before reaching the page,
// otherwise a field containing markup would be interpreted by the browser
echo "<th>" . htmlspecialchars((string) $column, ENT_QUOTES, "UTF-8") . "</th>";
}
echo "</tr>";
$count = 0;
while (($row = fgetcsv($handle, 0, ",")) !== false) {
if ($row === array(null)) { // ignore a blank line
continue;
}
if (count($row) !== count($header)) { // a malformed record, report and skip it
echo "<tr><td colspan='" . count($header) . "'>Skipped a record with the wrong number of fields.</td></tr>";
continue;
}
$record = array_combine($header, $row); // field name to field value
echo "<tr>";
foreach ($record as $value) {
echo "<td>" . htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8") . "</td>";
}
echo "</tr>";
$count++;
}
echo "</table>";
fclose($handle);
echo "<p>Total records read: " . $count . "</p>";
?>
What the page shows
| Name | Age | City |
|---|---|---|
| Alice | 23 | Kathmandu |
| Bob | 25 | Pokhara |
| Charlie | 22 | Lalitpur |
followed by the line Total records read: 3.
Functions used
| Function | Purpose |
|---|---|
fopen($file, "r") | Opens the file for reading and returns a handle |
fgetcsv($handle, 0, ",") | Reads the next record and returns its fields as an array |
array_combine($keys, $values) | Builds an associative record from the header names and the field values |
fclose($handle) | Closes the file when the loop ends |
str_getcsv($line) | Parses a single CSV line already held in a string |
Because $record is keyed by column name, a particular field can be printed directly, for example htmlspecialchars($record["City"], ENT_QUOTES, "UTF-8"), without depending on the position of that column in the file. That makes the script survive a reordering of the columns, which a program indexing by $row[2] would not.
Two points decide whether such a script is correct in practice. The record must be read with fgetcsv() or str_getcsv() rather than explode(",", $line), because the quoting rule means a comma inside a quoted field is data and not a separator. And every value taken from the file must pass through htmlspecialchars() before it is echoed, since the file is input from outside the program and an unescaped field is a stored cross site scripting hole in the page that displays it.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.