How can the use of fgets() in PHP be optimized for handling different types of text file formats and line endings?

When using fgets() in PHP to read text files with different formats and line endings, it is important to set the length parameter to a higher value to accommodate longer lines. Additionally, using trim() function can help remove any extra whitespace characters, including newlines, carriage returns, and spaces. Lastly, using the PHP_EOL constant can help handle different line endings across different operating systems.

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

while (!feof($file)) {
    $line = trim(fgets($file, 4096));
    // Process the line here
}

fclose($file);