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

Detailed explanation of fgets() function in PHP

autoload
Release: 2023-04-09 21:46:02
Original
2672 people have browsed it

  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 = ? )
Copy after login
  • $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?
Copy after login

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>";
Copy after login
输出:
php good better Knowledge is power
我有一件小法宝
PHP is the best language for web programming, but what about other languages?
Copy after login

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>";
Copy after login
输出:php good 
      better Kn
      owledge i
Copy after login

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!

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