Home > Backend Development > PHP Tutorial > Read file line by line using PHP

Read file line by line using PHP

PHPz
Release: 2023-09-04 18:54:02
Original
1863 people have browsed it

There are two reasons why you might want to use PHP to read a file line by line:

  1. The project you are working on requires you to process the file one line at a time.
  2. You are reading a very large file, and the only way to read it without exceeding the memory limit is to read it one line at a time.

Use file() to read the file

You can use the file() function in PHP to read the entire file into an array at once. The array elements are individual lines of the file. So you will be able to iterate over the lines in the file by iterating through the array. This function accepts three parameters:

  • Filename: This is the file you want to read. You can also provide a URL as the file name.
  • flags: This is an optional parameter that can be set to one or more of the following constant values: FILE_USE_INCLUDE_PATH, FILE_IGNORE_NEW_LINES, and FILE_SKIP_EMPTY_LINES.
  • Context: This is also an optional parameter used to modify the behavior of the stream.

We will use the FILE_SKIP_EMPTY_LINES flag to skip all empty lines in the file. You may also want to use FILE_IGNORE_NEW_LINES to remove line endings from individual lines.

This function returns an array containing the file contents on success and false on failure. If the file does not exist, you will also receive an E_WARNING level error. Here is an example of using this feature.

<?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;
}

?>
Copy after login

The output of the above code is as follows:

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]
Copy after login

You can see that there are some empty lines in the output; we can use the FILE_SKIP_EMPTY_LINES flag to get rid of them. Also, it might not be obvious, but the line above contains newlines. That's why we don't have to add our own newlines when echoing these lines. You can use the FILE_IGNORE_NEW_LINES flag to remove empty lines.

<?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;
}

?>
Copy after login

Output with these 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] 
Copy after login

If you are not worried about memory usage, using the file() function is an easy way to read a file line by line in PHP. However, if memory usage is an issue, you'll have to get more creative, since file() will read the entire file into an array at once.

Use fgets() to read files

Another way to read a file line by line using PHP is to use the fgets() function. It has one required parameter, which is a valid file handle. We will use the fopen() function to access the file handle. This is the code we want to run:

<?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);

?>
Copy after login

In the first line, we open the file in read-only mode. Then, we define a function that accepts $file_handle as a parameter and returns a row. Note that we are using a yield statement and that our function get_all_lines() is a generator function. If you haven't used generator functions in PHP before, you might want to read about them.

  • Read file line by line using PHP

我们在 get_all_lines() 中使用 feof() 函数来检查文件指针是否到达文件末尾。只要我们不在文件末尾,我们就会屈服。通过运行上面的代码,您应该得到以下输出:

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]
Copy after login

输出看起来与我们上一节中的相同。这次唯一的区别是您不再面临内存不足的危险。

我之前提到过 fgets() 将允许您一次读取文件的一行,并且它只需要一个指向您要读取的文件的文件指针的参数。在这种情况下,内存消耗取决于行的长度,并且内存不足的可能性很小。

但是,假设您正在阅读一个包含异常长行的文本文件。然后,您可以将可选的第二个参数传递给 fgets() 函数,该函数指定要读取的字符数。然后,它将在停止之前从文件中读取 length - 1 字节。如果遇到新行或文件末尾,它将提前停止。这使您可以更好地控制代码的内存消耗。

最终想法

我在本教程中讨论了两种使用 PHP 逐行读取文件的方法。还有几种方法可以做到这一点,但这两种方法几乎可以满足您的所有需求。当内存消耗不是问题时,请使用 file() 函数,如果您想节省内存,请使用 fgets() 和生成器函数。

The above is the detailed content of Read file line by line using PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Previous article:Quick Tip: Add Custom Columns in WordPress Admin Screen Next article:Get first and last element of PHP array
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template