How can the trim() function be used to handle newline characters when reading text files in PHP?

When reading text files in PHP, newline characters at the beginning or end of a string can sometimes cause issues. To handle this, you can use the trim() function to remove any leading or trailing whitespace characters, including newline characters. This ensures that the string is clean and does not contain any unwanted characters.

$file = fopen("example.txt", "r");
while(!feof($file)){
    $line = trim(fgets($file));
    // Process the line here
}
fclose($file);