Home  >  Article  >  Backend Development  >  How to use php fgets() function

How to use php fgets() function

青灯夜游
青灯夜游Original
2021-07-05 19:03:162303browse

In PHP, the fgets() function is used to read one line of data at a time from an open file, with the syntax format "fgets(file,length)". The fgets() function will stop returning a new line when it reaches the specified length "length-1", encounters a newline character, or reaches the end of the file (whichever comes first).

How to use php fgets() function

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In php, fgets() The function reads data one line at a time from an open file. The syntax format of the function is as follows:

fgets(file,length)
Parameters Description
file Required. Specifies the file to be read.
length Optional. Specifies the length of data to be read (number of bytes). The default is 1024 bytes.

The function can read a line from the specified file $file and return a maximum length of $length-1 A string of bytes. Stops after encountering a newline character, EOF, or reading $length-1 bytes. If the $length parameter is omitted, the default read length is 1k (1024 bytes).

Example:

Use the fgets() function to read the contents of the file line by line and output it.

<?php
    $handle = @fopen("./test.txt", "r");
    if ($handle) {
        while (($info = fgets($handle, 1024)) !== false) {
            echo $info.&#39;<br>&#39;;
        }
        fclose($handle);
    }                                
?>

The running results are as follows:

php中文网
https://www.php.cn/

Recommended learning: "PHP Video Tutorial"

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!

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