![]() ![]() Inside the if block, we read the first line of our file and if it is not strictly equal to false we enter the while loop and process the whole file one line at a time. PHP $handle = fopen("life-of-the-bee.txt", "r") Unless the file that you are reading has very long lines, you won’t exhaust your memory like you could with the file() function in previous section. In other words, the maximum memory that you need with fgets() depends on the longest line in the file. If you have not specified a particular length that this function should read, it will read the whole line. This means that we can check if a file has been read completely by comparing the return value of fgets() to false. ![]() It also returns FALSE if there is no more data to be read. The function stops reading after reaching a specified length, encountering a new line or reaching the end of file. The fgets() function in PHP reads the current line from an open file pointed to by the resource handle. Reading a Large File One Line at a Time Using fgets() Now we will learn how to read a file that might be over 1GB in size without exhausting our memory. This file is just 360kb long so reading it using the file() function was not a problem. In the example above, I have read a text file called The Life of the Bee from Project Gutenberg. Output - Total number of short lines: 778.Įcho "Total number of short lines: $short_lines.\n" PHP $life_of_bee_lines = file('life-of-the-bee.txt') Įcho "Total Lines: ".count($life_of_bee_lines).".\n" This means that you won’t be able to use it to read very large files. In other words, it solves the problem of reading a file one line at a time but it still reads the whole file at once. One major drawback of this method is that it will read the whole file at once. ![]() If you intended to read a file line by line and store the result in an array, the file() function seems to a natural choice. This function stores each line along with the newline character in its own array element. You can use the file() function in PHP to read an entire file into an array. Reading a File Line by Line into an Array Using file() Reading a Large File in Smaller Pieces Using fread().Reading a Large File One Line at a Time Using fgets().Reading a File Line by Line into an Array Using file(). ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |