File And Directory Manipulation In PHP (part 1) - Different Strokes (Page 3 of 9 )
An alternative way to accomplish the same thing is to use the fgets() function in combination with the feof() function, as demonstrated below:
<?php
// set file to read
$filename = "mindspace.txt";
// open file
$fh = fopen ($filename, "r") or die("Could not open file");
// read file
while (!feof($fh))
{
$data = fgets($fh);
echo $data;
}
// close file
fclose ($fh);
echo "-- ALL DONE --";
?>
The fgets() function works slightly differently from the fread() function, in that it reads a file line by line until the end of the file is reached (the feof() function is used to test for the end-of-file marker).
There are also a couple of other methods of reading data from a file - the very cool file() function, which reads the entire file into an array with one fell swoop, assigning each line as an element of the array. The following example demonstrates:
<?php
// set file to read
$filename = "mindspace.txt";
// read file into array
$data = file($filename) or die("Could not read file!");
// loop through array and print each line
foreach ($data as $line)
{
echo $line;
}
// print file contents
echo "-- ALL DONE --";
?>
As you can see, this example assigns the contents of the file "mindspace.txt" to the array variable $data via the file() function. Each element of the array variable now corresponds to a single line from the file. Once this has been done, it's a simple matter to run through the array and display its contents with the "foreach" loop.
Don't want the data in an array? Try the new file_get_contents() function, which reads the entire file into a string,
<?php
// set file to read
$filename = "mindspace.txt";
// read file into string
$data = file_get_contents($filename) or die("Could not read file!");
// print file contents
echo $data . "-- ALL DONE --";
?>
or use the readfile() function, which reads a file and dumps it directly to the standard output device (in the case of PHP, usually the Web browser):
<?php
// set file to read
$filename = "mindspace.txt";
// read and output file
readfile($filename) or die("Could not read file!");
echo "-- ALL DONE --";
?>
Next: Weapon Of Choice >>
More PHP Articles
More By icarus, (c) Melonfire