Reading and Writing Files

4.63 (76)

Reading Files

Reading files can be very important for certain applications, such as template systems, calculations and statistics. Hence, we will first concentrate on reading our sayings file. There are two main methods of reading files in PHP, and they are line-by-line or all in one by block. We are going to first read the entire file into a big block and output it:

Read Entire File
<?php
if (!$file fopen('randomsayings.txt''rb')) {
    echo 
'Error whilst opening the file.';
} else {
    
$data '';
    while (!
feof($file)) {
        
$data .= fread($file4096);
    }

    echo 
$data;
    
fclose($file);    
}

?>


Here we have expanded upon our last script, however, we have changed the file mode to read-only in binary mode. What this script does is first open the file, and then begins to read blocks of 4096 bytes into the variable called $data. Once it has completed, it prints the data and closes the file.

We have two new functions in this example; fread() and feof(). In order to read a block of data from a file and ignore new lines, then we must use the fread() function. This function, takes two parameters; the file resource, and the length of the data to read in each pass. Generally a value like 4096 or a little smaller is chosen, but it isn't too important.

The other new function, feof() returns a Boolean value depending on if we are at the end of the file that we are reading. This is the most common method of checking if we have read all the available data.

This script only writes out all the data straight to screen and would be difficult to beautify it's output to screen. In order to do this, it would be more useful to read line-by-line.

Reading Line-by-Line


In order to read line-by-line we have to replace our fread() function with fgets(). This function does take into account line endings, and will not read past them, until you call the function again. Once you call it again, it will continue to the next line.

We must also store our input data in a different format as we want to be able to individually access each line. Hence, it would be wise to store the lines in an array:

Line-by-Line
<?php
if (!$file fopen('randomsayings.txt''rb')) {
    echo 
'Error whilst opening the file.';
} else {
    
$data = array();
    while (!
feof($file)) {
        
$data[] = fgets($file);
    }

    
print_r($data);
    
fclose($file);    
}

?>


Here we can see that the respective functions have been replaced, and now $data is an array instead of just a string. Then, the structure of the array is printed using print_r($data). This creates the following output:

Array
(
[0] => Patience is a virtue.

[1] => Three's a crowd.

[2] => 43% of all statistics are wrong.

[3] => There are 10 types of people; those who understand binary and those who don't.

[4] => After all is said and done, more is said than done.

[5] => The biggest man you ever did see was once a baby.

[6] => It's only a game!
)


Now that we have all our lines correctly in an array, which has one element per line, we can create our random saying generator. This is just a simple random number generator based on the number of elements / sayings in our array.

Random Saying
<?php
if (!$file fopen('randomsayings.txt''rb')) {
    echo 
'Error whilst opening the file.';
} else {
    
$data = array();
    while (!
feof($file)) {
        
$data[] = fgets($file);
    }

    
fclose($file);    


    
$max count($data) - 1;
    
$random rand(0$max);

    echo 
'<b>Saying of the day:</b> ' $data[$random];
}
?>


This shouldn't look too complicated now. Only a few modifications have been made, in that we now do not print the entire contents to screen, we generate a random number and then print only one of the sayings.

The function rand() takes two important parameters; minimum integer and maximum integer. These define the range of the random number (integer) that will be generated and is inclusive. Hence, if we specify 0 and 5, the numbers 0-5 can be generated. This is a very simple and not so random, random number generator, however it will do for our purposes.

With the random number generator, we pass the lowest index (0) and the highest index of the array so that all possible array indexes can be generated. In order to find the maximum, we just use count($data)-1 to get the value of the last index in the array. We can now output our random sayings!



But what if you want to add new sayings?
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 2 of 3    >>

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter