What is the function of fgets in PHP and how is it used to read a line from a file?

The function of fgets in PHP is to read a line from a file. It reads a line of text from the file pointer and returns it as a string. To use fgets to read a line from a file, you need to open the file using fopen, then use fgets in a loop to read each line until the end of the file is reached.

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

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