Read file line by line using PHP
There are two reasons why you might want to use PHP to read a file line by line:
- The project you are working on requires you to process the file one line at a time.
- 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
, andFILE_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; } ?>
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]
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; } ?>
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]
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); ?>
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.
我们在 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]
输出看起来与我们上一节中的相同。这次唯一的区别是您不再面临内存不足的危险。
我之前提到过 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.
