How to use php fgets function

藏色散人
Release: 2023-02-22 21:44:01
Original
2630 people have browsed it

php The fgets function is used to read a line from the file pointer. Its syntax is fgets(file,length). The parameter file is required and specifies the file to be read.

How to use php fgets function

#How to use php fgets function?

Definition and usage

fgets() function reads a line from the file pointer.

Syntax

fgets(file,length)
Copy after login

Parameters

file Required. Specifies the file to be read.

length Optional. Specifies the number of bytes to read. The default is 1024 bytes.

Description

Reads a line from the file pointed to by file and returns a string with a length of at most length - 1 bytes. Stops on encountering a newline character (included in the return value), EOF, or after length - 1 bytes have been read (whichever occurs first). If length is not specified, it defaults to 1K, or 1024 bytes.

If it fails, return false.

Tips and Notes

Note: The length parameter is optional as of PHP 4.2.0, and 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 don't.

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

Example 1

<?php
$file = fopen("test.txt","r");
echo fgets($file);
fclose($file);
?>
Copy after login

Output similar to:

Hello, this is a test file.
Copy after login

Example 2

<?php
$file = fopen("test.txt","r");
while(! feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);
?>
Copy after login

Output similar to:

Hello, this is a test file. 
There are three lines here. 
This is the last line.
Copy after login

The above is the detailed content of How to use php fgets function. 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