HTML, XHTML and CSS All-In-One for Dummies - Andy Harris [230]
Reading from the file
If you can write data to a file, it would make sense that you could read from that file as well. The showContacts.php program displayed in Figure 6-3 pulls the data saved in the previous program and displays it to the screen.
Figure 6-3: This program reads the text file and displays it onscreen.
It is not difficult to write a program to read a text file. Here’s the code:
Contacts
//open up the contact file
$fp = fopen(”contacts.txt”, ”r”) or die(”error”);
//print a line at a time
while (!feof($fp)){
$line = fgets($fp);
print ”$line
”;
}
//close the file
fclose($fp);
?>
The procedure is similar to writing the file, but it uses a for loop.
1. Open the file in read mode.
Open the file just as you do when you write to it, but use the r designator to open the file for read mode. Now you can use the fgets() function on the file.
2. Create a while loop for reading the data.
Typically, you’ll read a file one line at a time. You’ll create a while loop to control the action.
3. Check for the end of the file with feof().
You want the loop to continue as long as there are more lines in the file. The feof() function returns the value true if you are at the end of the file, and false if there are more lines to read. You want to continue as long as feof() returns false.
4. Read the next line with the fgets() function.
This function reads the next line from the file and passes that line into a variable (in this case, $line).
5. Print out the line.
With the contents of the current line in a variable, you can do whatever you want with it. In this case, I’ll simply print it out, but you could format the contents, search for a particular value, or whatever else you want.
Why not just link to the file?
If this program just prints out the contents of a text file, you might wonder why it’s necessary at all. After all, you could just supply a link to the text file. For this trivial example, that might be true, but the process of reading the file gives you many other options. For example, you might want to add improved CSS formatting. You might also want to filter the contents: for example, only matching the lines that relate to a particular entry. Finally, you may want to do more than print the contents of a file — say, e-mail them or transfer them to another format. When you read the contents into memory, you can do anything to them.
Using Delimited Data
This basic mechanism for storing data is great for small amounts of data, but it will quickly become unwieldy if you’re working with a lot of information.