There are two reasons why you might want to read a file line by line with PHP. The first is that the project you are working on requires you to process the file one line at a time. The second is that you are reading a very large file and the only way to read it without exceeding the memory limit is to do it one line at a time.
Using file()
to read the file
You can use the file()
function in PHP to read the entire file at once into an array. The elements of the array are single lines of the file. Then you will be able to iterate through the lines in the file by iterating over the array. The function accepts three parameters:
- file name: This is the file you want to read. You can also provide a URL as a filename.
-
flags: This is an optional parameter and can be set to one or more of the following constant values:
FILE_USE_INCLUDE_PATH
,FILE_IGNORE_NEW_LINES
AndFILE_SKIP_EMPTY_LINES
. - context: This is also an optional parameter used to change the behavior of a stream.
We will use the FILE_SKIP_EMPTY_LINES
flag to skip all blank lines in a file. You may also want to use FILE_IGNORE_NEW_LINES
to remove line endings from individual lines.
This function returns an array with the contents of the file on success and false
to bankruptcy. You will also receive a E_WARNING
level error if the file does not exist. Here is an example of using this function.
<?php $lines = file('pride-and-prejudice.txt'); $count = 0; foreach($lines as $line) { $count += 1; echo str_pad($count, 2, 0, STR_PAD_LEFT).". ".$line; } ?>
The output from the code above looks like this:
01. The Project Gutenberg eBook of Pride and Prejudice, by Jane Austen 02. 03. This eBook is for the use of anyone anywhere in the United States and 04. most other parts of the world at no cost and with almost no restrictions 05. whatsoever. You may copy it, give it away or re-use it under the terms 06. of the Project Gutenberg License included with this eBook or online at 07. www.gutenberg.org. If you are not located in the United States, you 08. will have to check the laws of the country where you are located before 09. using this eBook. 10. 11. Title: Pride and Prejudice 12. 13. Author: Jane Austen 14. 15. Release Date: June, 1998 16. [Most recently updated: August 23, 2021]
You can see there are some blank lines in the output, we can get rid of them using the FILE_SKIP_EMPTY_LINES
flag. Also, it may not be obvious, but the lines above include the newline character. This is why we didn’t have to add our own newline character while echoing the lines. You can get rid of the blank lines by using the FILE_IGNORE_NEW_LINES
flag.
<?php $lines = file('pride-and-prejudice.txt', FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES); $count = 0; foreach($lines as $line) { $count += 1; echo str_pad($count, 2, 0, STR_PAD_LEFT).". ".$line; } ?>
The output with those flags will look like this:
01. The Project Gutenberg eBook of Pride and Prejudice, by Jane Austen 02. This eBook is for the use of anyone anywhere in the United States and 03. most other parts of the world at no cost and with almost no restrictions 04. whatsoever. You may copy it, give it away or re-use it under the terms 05. of the Project Gutenberg License included with this eBook or online at 06. www.gutenberg.org. If you are not located in the United States, you 07. will have to check the laws of the country where you are located before 08. using this eBook. 09. Title: Pride and Prejudice 10. Author: Jane Austen 11. Release Date: June, 1998 [eBook #1342] 12. [Most recently updated: August 23, 2021]
Using the file()
The function is an easy way to read a file line by line in PHP if you’re not worried about memory usage. However, you will need to get more creative if memory usage is an issue because file()
read the entire file into an array at once.
Using fgets()
to read the file
Another way to read a file line by line with PHP is to use the file fgets()
function. It has a required parameter which is a valid file handle. We will use the fopen()
function to gain access to the file handle. Here is the code we will execute:
<?php $file_handle = fopen('pride-and-prejudice.txt', 'r'); function get_all_lines($file_handle) { while (!feof($file_handle)) { yield fgets($file_handle); } } $count = 0; foreach (get_all_lines($file_handle) as $line) { $count += 1; echo $count.". ".$line; } fclose($file_handle); ?>
In the first line, we open our file in read-only mode. So, we define a function that accepts a $file_handle
as a parameter and returns a single row. Please note we are using a yield
statement and our function get_all_lines()
it is a function of the generator. You may want to read generator functions in PHP if you have never used them before.
We are using the feof()
function inside get_all_lines()
to check if our file pointer has reached the end of the file. We only give in until we are at the end of the file. You should get the following output by running the above code:
1. The Project Gutenberg eBook of Pride and Prejudice, by Jane Austen 2. 3. This eBook is for the use of anyone anywhere in the United States and 4. most other parts of the world at no cost and with almost no restrictions 5. whatsoever. You may copy it, give it away or re-use it under the terms 6. of the Project Gutenberg License included with this eBook or online at 7. www.gutenberg.org. If you are not located in the United States, you 8. will have to check the laws of the country where you are located before 9. using this eBook. 10. 11. Title: Pride and Prejudice 12. 13. Author: Jane Austen 14. 15. Release Date: June, 1998 16. [Most recently updated: August 23, 2021]
The releases look the same as in our previous section. The only difference this time is that you no longer run the risk of running out of memory.
I mentioned it before fgets()
will allow you to read one line of the file at a time and only requires a single parameter that points to the file pointer for the file you want to read. The memory consumption in this case would depend on the length of the line and there is a small chance that you will run out of memory.
However, let’s say you are reading a text file that contains unusually long lines. You can then pass an optional second parameter to fgets()
function that specifies the number of characters you want to read. We will then read length - 1
bytes from the file before stopping. It will stop earlier if it encounters a new line or the end of the file. This gives you more control over the memory consumption of your code.
Final thoughts
I have discussed two methods of reading a file line by line with PHP in this tutorial. There are a couple of other ways to do this, but these two will meet almost all of your needs. Use the file()
function when memory consumption is not a problem and use fgets()
with a generator function if you want to save memory.