File Read and Write
PHP offers quite a range of methods to read and write files. In the case below, I have chosen just to create and then read a simple three (3) field data base stored as a tab delimited text file. See http://au2.php.net/manual/en/ref.filesystem.php for much more detail and options.
Read a tab delimited text file
Write a program that will read three fields from a text file in tab delimited format and display the content on the screen.
The content of the file is <string field><tab><string field><tab><integer field><new line>
<?php
//File tab delimited file read in PHP and designed for use at the command line
fwrite(STDOUT, "\n Given \t Surname \t Age \n");
fwrite(STDOUT, "---------------------------------------------------------- \n");
if ( $fp = fopen('friends.txt','r') ) {
while ($friendinfo = fscanf($fp, "%s\t%s\t%d\n")) {
list ($given, $surname, $age) = $friendinfo;
fwrite(STDOUT, $given." \t".$surname." \t".$age."\n");
}
fclose($fp);
}
else
{
fwrite(STDOUT, "file not found \n");
}
exit(0);
?>
Note:
fopen creates a hadle to the file.
fopen returns false if the file does not exist so an if staement can be used to test if the file exists.
fscanf returns a false when the end of file is reached so the while lop can be terminated.
Write a tab delimited text file
Write a program that will accept values from the user and write them to a tab delimited text file.
The content of the file is <string field><tab><string field><tab><integer field><new line>
<?php
//File tab delimited file write (append) in PHP and designed for use at the command line
if ( $fp = fopen('friends.txt','at') ) {
fwrite(STDOUT, "how many friends do you want to enter --> ");
fscanf(STDIN, "%d\n", $friends);
for ($i=0; $i < $friends; $i++) {
fwrite(STDOUT, "enter given name--> ");
fscanf(STDIN, "%s\n", $given);
fwrite(STDOUT, "enter surname--> ");
fscanf(STDIN, "%s\n", $surname);
fwrite(STDOUT, "enter age--> ");
fscanf(STDIN, "%d\n", $age);
//write date to file
fwrite($fp, $given." \t".$surname." \t".$age."\n");
}
fclose($fp);
}
else
{
fwrite(STDOUT, "file not found \n");
}
exit(0);
?>
Note:
The "a" parameter in the fopen function allows you to append to a file. The "t" parameter is for Windows files only and is to endure that a CR LF sequence is put at the end of the record.
Exercises
- Create a simple database management system by combining the two programs above into procedures. Then use an array to store your data while in memory. Create a simple sort function that will sort your data into age order.
- ex2
- ex3
Comments (0)
You don't have permission to comment on this page.