What is the issue with using the substr function in PHP to extract the beginning of each line from a text file?

The issue with using the substr function in PHP to extract the beginning of each line from a text file is that it may not handle different line endings properly, leading to unexpected results. To solve this issue, it's better to use the fgets function to read each line from the file and then use substr to extract the desired portion of each line.

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

if ($file) {
    while (($line = fgets($file)) !== false) {
        $beginning = substr($line, 0, 10); // Extract the first 10 characters of each line
        echo $beginning . PHP_EOL;
    }
    
    fclose($file);
} else {
    echo "Error opening file.";
}