Web Technology II · Unit 9
File Handling and Data Formats
Exam-focused notes for File Handling and Data Formats (Web Technology II, BIT301): what the TU syllabus asks and how it has actually been tested, with 5 solved past questions from this unit.
File Handling and Data Formats in short
PHP can read and write files on the server. It can also read common data formats such as CSV and JSON, which are used to store and exchange data.
What this unit covers
- File reading operations
- File writing operations
- File operations and I/O
- JSON file parsing and reading
- CSV file parsing and processing
- File content display
CSV file parsing and processing
2082 · 5 marks
Write a program to parse a CSV file and display the content in the file. [5]
Show solved answerHide answer
Reading a CSV file and displaying its contents
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.
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.
File reading operations
File writing operations
JSON file parsing and reading
2079 · 5 marks
For the following JSON file named BIT.JSON, write a PHP program to read information from this JSON file: {Name: "Gunadi", Email: "[email protected]", Dob: "January 1", Age: 30} [5]
Make Unit 9 stick
Practice BIT301 with flashcards & quizzes