How can you ensure consistent formatting when reading files with fgets in PHP?

When reading files with fgets in PHP, inconsistent formatting can occur if the file contains different line endings (e.g., Windows CRLF, Unix LF). To ensure consistent formatting, you can use the rtrim() function to remove any trailing whitespace characters, including different line endings, from each line read by fgets.

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

if ($file) {
    while (($line = fgets($file)) !== false) {
        $line = rtrim($line); // Remove trailing whitespace characters
        // Process the line here
    }

    fclose($file);
} else {
    echo "Error opening file.";
}