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

不言
Release: 2023-04-05 11:30:02
Original
4458 people have browsed it

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

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);
?>
Copy after login

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);
?>
Copy after login

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);
?>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!