What are some common pitfalls when using fgets to read files in PHP?

One common pitfall when using fgets to read files in PHP is not handling the newline character at the end of each line properly. This can lead to unexpected behavior or errors in your code. To solve this issue, you can use the rtrim function to remove any trailing newline characters from the line read by fgets.

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

if ($file) {
    while (($line = fgets($file)) !== false) {
        $line = rtrim($line, "\n");
        // Process the line here
    }
    fclose($file);
} else {
    echo "Error opening file.";
}