Home >Backend Development >PHP Tutorial >Detailed explanation of fgets() function in PHP

Detailed explanation of fgets() function in PHP

autoload
autoloadOriginal
2021-04-21 11:13:412666browse

  Detailed explanation of fgets() function in PHP

        PHP often needs to read files. Sometimes we may need to read a line of information from the specified file, so how do we solve this problem Woolen cloth? PHP has a built-in fgets() function, which can return a line from the opened file. This article will take you to take a look.

The first thing you need to understand is the syntax:

fgets ( resource $handle , int $length = ? )
  • $handle: the file pointer must be valid and must point to the file specified by fopen() or fsockopen() File opened successfully (not yet closed by fclose()).

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

  • Return value: Returns a string after reading $length - 1 bytes from the file pointed to by the pointer $handle . If there is no more data in the file pointer, false is returned. Returns false when an error occurs.

Code example:

With read file information:

//exit.txt
php good better Knowledge is power
我有一件小法宝
PHP is the best language for web programming, but what about other languages?

1. There is only one parameter $handle

<?php
$resource=fopen("./exit.txt","r");
echo fgets($resource)."<br>";
echo fgets($resource)."<br>";
echo fgets($resource)."<br>";
输出:
php good better Knowledge is power
我有一件小法宝
PHP is the best language for web programming, but what about other languages?

2. There are two parameters $handle, $length

<?php
$resource=fopen("./exit.txt","r");
echo fgets($resource,10)."<br>";
echo fgets($resource,10)."<br>";
echo fgets($resource,10)."<br>";
输出:php good 
      better Kn
      owledge i

Recommended: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of Detailed explanation of 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