An alternative way to accomplish the same thing is to use the fgets() function in combination with the feof() function, as demonstrated below:
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:
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,
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):
blog comments powered by Disqus |