Working with text files - Other functions regarding text files
(Page 7 of 10 )
There are a few other functions which we did not talk about in previous chapters. We can learn about them one by one in this chapter.
fgets()
In case you want to read a file one line at a time, this is what you need.
<?php $buffer = fgets( $fp, 100); ?>
In this case, this script will read until it finds a new line character (\n), encounters an EOF, or has read 99 bytes from the file. The maximum length read is the length specified minus one byte. The fgets() function is useful when dealing with files that contain plain text that we want to deal with in chunks.
This function takes file pointer as its single parameter. It will return true if the file pointer is end of file and false if it is somewhere else in the file. We commonly use this function when looping through a file until the end of file.
The above example simply outputs the content in the text file which is opened in the first line of the script. This uses the feof() function which is mentioned above and it read the file until EOF file occurs. While running the loop it echos the content read line by line fgets() function!
readfile()
Instead of reading line by line, we can read the whole file in one go with readfile(). Secondly this automatically echos the contents of the file to the browser without adding echo() or print(). Unlike other functions this takes the parameter of filename with the path of it, not a file pointer.
This is a very important function when it comes to file reading. It also identical to the readfile() except that instead of echoing the file as an output, it turns it into an array. Elements of the array will be the lines of the opened file. We'll go through this function with more details in examples at the end of the tutorial.