Skip to content
PHP Logo

What is the purpose of using fgets() in PHP and how does it work?

The purpose of using fgets() in PHP is to read a single line from a file. It is commonly used to read text data from files line by line. fgets() works by reading a line of text from the file pointer and moving the pointer to the next line.

php
$file = fopen("example.txt", "r");

if ($file) {
    while (($line = fgets($file)) !== false) {
        echo $line;
    }
    fclose($file);
}