HomePHP Page 3 - File And Directory Manipulation In PHP (part 1)
Different Strokes - PHP
PHP comes with a powerful and flexible file manipulation API that allows developers (among other things) to read and write files, view and modify file attributes, read and list directory contents, alter file permissions, and retrieve file contents into a variety of native data structures. Find out more, inside.
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!");