Specifications

FIGURE 2.4
The vieworders.php script displays all the orders currently in the orders.txt file in the browser window.
Lets look at the functions in this script in detail.
Opening a File for Reading: fopen()
Again, we open the file using fopen(). In this case we are opening the file for reading only, so
we use the file mode “r”:
$fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, “r”);
Knowing When to Stop: feof()
In this example, we use a while loop to read from the file until the end of the file is reached.
The while loop tests for the end of the file using the feof() function:
while (!feof($fp))
The feof() function takes a file pointer as its single parameter. It will return true if the file
pointer is at the end of the file. Although the name might seem strange, it is easy to remember
if you know that feof stands for File End Of File.
In this case (and generally when reading from a file), we read from the file until EOF is
reached.
Reading a Line at a Time: fgets(), fgetss(), and fgetcsv()
In our example, we use the fgets() function to read from the file:
$order= fgets($fp, 100);
This function is used to read one line at a time from a file. In this case, it will read until it
encounters a newline character (\n), encounters an EOF, or has read 99 bytes from the file. The
maximum length read is the length specified minus one byte.
Using PHP
P
ART I
60
04 7842 CH02 3/6/01 3:37 PM Page 60