Home  >  Article  >  Backend Development  >  How to read a file line by line using fgets() function in php

How to read a file line by line using fgets() function in php

不言
不言Original
2019-02-22 10:17:594477browse

The fgets() function in How to read a file line by line using fgets() function in php is used to read a single line of content from a file, so in this next article we will take a closer look at how to use the fgets() function in How to read a file line by line using fgets() function in php to read the file content line by line.

How to read a file line by line using fgets() function in php

The basic syntax of the fgets() function is as follows:

fgets(file, length)

file: Specify the file name to read the content

length: Optional parameter, specifying the number of bytes to read from the file.

Here are two examples of reading a single line from a file using How to read a file line by line using fgets() function in php.

Example 1: Read the first 20 bytes from the file

The code is as follows

<?How to read a file line by line using fgets() function in php
  $fn = fopen("myfile.txt","r");
  $result = fgets($fn, 20);
  echo $result;
  fclose($fn);
?>

Use this example to read from the file Get the complete first line of content.

<?How to read a file line by line using fgets() function in php
  $fn = fopen("myfile.txt","r");
  $result = fgets($fn);
  echo $result;
  fclose($fn);
?>

Example 2: Read all lines

Use a for loop to read all the lines in the file one by one, and use the How to read a file line by line using fgets() function in php feof() function to find the end of the file.

The code is as follows

<?How to read a file line by line using fgets() function in php
  $fn = fopen("myfile.txt","r");
  
  while(! feof($file))  {
	$result = fgets($fn);
	echo $result;
  }

  fclose($fn);
?>

This article has ended here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !

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

Statement:
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