9 File Handling And Data Formats

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.

File Handling and Data Formats: notes

File reading operations

The usual steps are: open the file, read it, close it. fopen() opens a file with a mode.

ModeMeaning
rread only, start at the beginning
wwrite only, empties the file or creates it
aappend at the end, creates it if missing
xcreate new file, fails if it exists
r+, w+, a+read and write
<?php
$fp = fopen("notes.txt", "r");
if (!$fp) {
    die("Cannot open file");
}
while (($line = fgets($fp)) !== false) {
    echo htmlspecialchars($line) . " ";
}
fclose($fp);

Reading functions:

  • fgets($fp) reads one line.
  • fgetc($fp) reads one character.
  • fread($fp, $bytes) reads a set number of bytes.
  • feof($fp) tells if the end of file is reached.
  • file_get_contents("notes.txt") reads the whole file as a string.
  • file("notes.txt") reads the file into an array, one line per item.

File writing operations

<?php
$fp = fopen("log.txt", "a");
fwrite($fp, "User logged in at " . date("H:i:s") . "\n");
fclose($fp);

file_put_contents("data.txt", "Hello\n");                    // overwrite
file_put_contents("data.txt", "More text\n", FILE_APPEND);   // append
  • fwrite() (also fputs()) writes a string.
  • file_put_contents() opens, writes and closes in one call.
  • Mode w removes the old content, so use a to keep it.
  • The web server user must have permission to write to the folder.
  • Use flock($fp, LOCK_EX) when many users may write at the same time.

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 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

NameAgeCity
Alice23Kathmandu
Bob25Pokhara
Charlie22Lalitpur

followed by the line Total records read: 3.

Functions used

FunctionPurpose
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.

Open this answer on its own page →

0 · 5 marks

Write a PHP program to parse a CSV file. [5]

A CSV file is plain text in which every line is one record and the fields inside a line are separated by a delimiter, normally a comma. PHP opens such a file with fopen() and then pulls one record at a time with fgetcsv(), which returns the fields of that record as an array and already understand...

Open this answer on its own page →

File reading operations

2081 · 5 marks

Write a PHP program to read a file. [5]

--- There are several ways to read a file in PHP. Below are the common approaches: --- --- --- --- Function Description ------ fopen($file, "r") Opens a file in read mode fgets($file) Reads one line from the file feof($file) Returns true if end of file is reached fclose($file) Closes the opened f...

Open this answer on its own page →

File writing operations

2080 · 5 marks

Write a PHP program to write on a file. [5]

PHP provides built-in functions to handle file operations. The most common approach uses fopen(), fwrite(), and fclose() functions. --- Function Description ----------------------- fopen(filename, mode) Opens a file; returns a file handle fwrite(handle, string) Writes a string to the file fclose(...

Open this answer on its own page →

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]

The listing in the question is written as a JavaScript object literal, with the property names bare: That is not valid JSON, and jsondecode() rejects it and returns null, because the JSON grammar requires every key to be a double quoted string. The file BIT.JSON must therefore hold the quoted for...

Open this answer on its own page →