Back to DFS's Workshop Page
Back to Agenda Page
Quick Links
Almost all Unix/Linux system files are saved as plain text. Typically, a single line will consist of several related items of information. This page will show you some ways of handling this situation.
An easy way to set up a multi-line file is to have the first line specify the number of other lines to be found in the file, e.g.,
3 Smoky|Burgess|337|99 Roberto|Clemente|570|179 Bill|Mazeroski|539|147
In many computer languages, an array can contain data of only one type, e.g., integer or string. In PHP, this restriction does not exist. The vertical bar character "|" is used here to separate the fields. So, the code to read in the information from the above file could be as follows:
$fp = fopen( "pirates1.dat", "r") or die("No such file!\n");
$num = trim(fgets($fp));
for( $i = 0; $i < $num; $i++)
{
$line = trim(fgets($fp));
$players[] = explode("|", $line);
}
fclose($fp);
The data is placed in the array so that the first name goes into the 0th, the last name into the 1st, etc. Batting averages can be calculated with the following code.
for($i = 0; $i < count($players); $i++) $players[$i]['Avg'] = $players[$i][3] / $players[$i][2];
You can see other ways of processing the resulting array by looking at the Using Two-Dimensional Arrays page.
Most system files contain comments as well as the data. The following file and code illustrate how you can add and handle such comments when reading in the file.
#First Name; Last Name; At Bats; Hits Smoky|Burgess|337|99 Roberto|Clemente|570|179 Bill|Mazeroski|539|147
$fp = fopen( "pirates2.dat", "r") or die("No such file!\n");
while( !feof($fp) )
{
$line = trim(fgets($fp));
if( ( strlen($line) > 0) && ($line[0] != "#") )
$players[] = explode("|", $line);
}
fclose($fp);
This code, besides skipping over comment lines beginning with the pound sign "#", will allow blank lines to be used as separators in the file.
To make your array-processing code more transparent, you may want to use descriptive subscripts instead of numeric ones. This is easily accommodated by using code such as the following.
#First Name; Last Name; At Bats; Hits Smoky|Burgess|337|99 Roberto|Clemente|570|179 Bill|Mazeroski|539|147
$fp = fopen( "pirates2.dat", "r") or die("No such file!\n");
while( !feof($fp) )
{
$line = trim(fgets($fp));
if( ( strlen($line) > 0) && ($line[0] != "#") )
{
list($pieces['fname'], $pieces['lname'],
$pieces['ABs'], $pieces['Hits']) = explode("|", $line);
$players[] = $pieces;
}
}
fclose($fp);
list() is used to place the data elements exploded from $line into a temporary array which is then assigned to the $players[][] array.
Batting averages can then be calculated and added to each record using code such as the following.
for($i = 0; $i < count($players); $i++) $players[$i]['Avg'] = $players[$i]['ABs'] / $players[$i]['Hits'];