File IO functions
fopen()
$fname = "guestBk.db";
$bytes = filesize($fname);
$fhand = fopen($fname, "r");
$contents = fread($fhand, $bytes);
fclose($fhand);
print($contents);
file_get_contents() and file() are simpler alternatives for
retreiving content from text files. The former requires a relatively
recent version of PHP, the latter returns an array of lines from the
file.
fgetcsv() -- this function is similar to fgets(),
except that it returns an array, using the specified delimiter, or comma
by default. Both will stop reading when they encounter a newline character.
while(
$myFieldsArr = fgetcsv($fhand, 1024)
){
list($name,$occ,$city,$state,$zip) = $myFieldsArr;
print("<tr><td>$name</td><td>$occ</td><td>$city</td>
<td>$state</td><td>$zip</td></tr>");
}
Of course it's best to check if the file_exists() and is_readable() before performing read operations. Otherwise, you may need to use the @ to ignore read errors, as for example, $f = @fopen("file.txt","r");
Note how the list() function initializes scalar variables to
specified names from the source array ($myFieldsArr). This is a useful
technique for making your code more legible.
|
|