How can the extra characters, such as line ending characters, be handled when reading lines with fgets in PHP?

When using fgets in PHP to read lines from a file, extra characters like line ending characters (such as newline, carriage return) may be included in the string. To handle this, you can use the rtrim function to remove any trailing whitespace characters, including line endings, from the end of the string.

$handle = fopen("file.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $line = rtrim($line);
        // Process the line without extra characters
        echo $line . PHP_EOL;
    }
    fclose($handle);
}