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()
函數(shù)來檢查文件指針是否到達文件末尾。只要我們不在文件末尾,我們就會屈服。通過運行上面的代碼,您應(yīng)該得到以下輸出:
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]
輸出看起來與我們上一節(jié)中的相同。這次唯一的區(qū)別是您不再面臨內(nèi)存不足的危險。
我之前提到過 fgets()
將允許您一次讀取文件的一行,并且它只需要一個指向您要讀取的文件的文件指針的參數(shù)。在這種情況下,內(nèi)存消耗取決于行的長度,并且內(nèi)存不足的可能性很小。
但是,假設(shè)您正在閱讀一個包含異常長行的文本文件。然后,您可以將可選的第二個參數(shù)傳遞給 fgets()
函數(shù),該函數(shù)指定要讀取的字符數(shù)。然后,它將在停止之前從文件中讀取 length - 1
字節(jié)。如果遇到新行或文件末尾,它將提前停止。這使您可以更好地控制代碼的內(nèi)存消耗。
最終想法
我在本教程中討論了兩種使用 PHP 逐行讀取文件的方法。還有幾種方法可以做到這一點,但這兩種方法幾乎可以滿足您的所有需求。當內(nèi)存消耗不是問題時,請使用 file()
函數(shù),如果您想節(jié)省內(nèi)存,請使用 fgets()
和生成器函數(shù)。
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

Undress AI Tool
Undress images for free

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

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

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

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
