PHP Programming Spring 2015
Exercise: File IO
1. Assign the pathname "slotcar.txt" to the variable $fName.
2. Show how to issue an open for reading from the file $fName and assign
the return value to a file pointer named $fpR. Include a clause to
print the message "File not found/opened" should there be an unsuccessful
attempt to open.
3. Open the file "slotcar.prn" for writing and and assign the return value to
$fpW. Include a clause to print the message "File not found/opened"
should there be an unsuccessful attempt to open.
4. Apply the fgets function to input a line of text from $fpR and assign
that string to $lineIn. Print (echo) $lineIn.
Given "slotcar.txt" has the following fixed-format layout: Id (an integer,
in positions 0-3, and the key); Brand (string, 5-13); Model (string,
15-25); Cost (float, two dec places, 27-33), quantity, 34; plus "newline".
5. Use the function substr ($fullStringName, $nameStart, $nameLength) to
extract the field components of $lineIn and assign to $id, $name,
$category, and $cost respectively.
6. Show how to use the fread function to input individual field values and
store in $id, $name, $category, $cost, and $quantity. Also input the
"newline" (two bytes on windows, one on unix/linux) to move the file
pointer to the start of the next line of data. Print (echo) $lineIn.
7. For the slotcar file "slotcar.csv" (delimited with commas instead of fixed
format) show how to use the fgetcsv function to input a line and store the
data in an array named $csvArray. After input, assign field values to the
array elements to $id, $name, etc (e.g. $id = $csvArray[0] ).
8. Apply the sprintf function [i.e. sprintf(formatSpecifier(s), identifiers)]
to format and assign the individual field values to a string named $linePrn.
9. Use the fwrite function (fwrite($fp, $identifier) to output $linePrn to
"slotcar.prn".
10. Close the files.