Home > Backend Development > PHP Tutorial > How to read a file line by line in php?

How to read a file line by line in php?

怪我咯
Release: 2023-03-13 13:32:01
Original
14561 people have browsed it

You can use PHPbuilt-in functionfgets() function in PHP, which reads a line from the file pointer.

Its syntax is as follows:

fgets(file,length)
Copy after login
ParametersDescription
fileRequired. Specifies the file to be read.
length Optional. Specifies the number of bytes to read. The default is 1024 bytes.

Read a line from the file pointed to by file and return a string of length at most length - 1 byte. Stops when a newline character (included in the return value), EOF, or length - 1 bytes has been read (whichever occurs first). If length is not specified, it defaults to 1K, or 1024 bytes.

If it fails, return false.

Note: The length parameter has become optional since PHP 4.2.0. If omitted, the length of the line is assumed to be 1024 bytes. Starting with PHP 4.3, omitting length will continue reading from the stream until the end of the line. If most of the lines in the file are larger than 8 KB, specifying the maximum line length in the script is more efficient in utilizing resources.

Note: Starting from PHP 4.3, this function can be safely used in binary files. Earlier versions did not.

Note: If you encounter that PHP cannot recognize the line ending characters of Macintosh files when reading files, you can activate the auto_detect_line_endings runtime configuration option.

The following is an example, the code is as follows

$filepath =  $_SERVER['DOCUMENT_ROOT'];  
  $filename = $filepath."/resource/dat/users.txt";
  $handle  = fopen ($filename, "r");
  //$contents = fread ($handle, filesize ($filename));
//echo $contents;
  
  while (!feof ($handle)) 
  {
    $buffer  = fgets($handle, 4096);
    
    $username = trim($buffer);
    echo $username
    }
 fclose ($handle);
Copy after login

The above is the detailed content of How to read a file line by line in php?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template