What best practices should be followed when handling CSV data in PHP to avoid issues like extra characters or line breaks affecting the output?

When handling CSV data in PHP, it is important to properly handle line breaks and extra characters to avoid issues with the output. One way to do this is by using the fgetcsv() function to read the CSV file line by line and parse it into an array. Additionally, trimming each value to remove any leading or trailing whitespace can help prevent extra characters from causing problems in the output.

$handle = fopen('data.csv', 'r');

while (($data = fgetcsv($handle)) !== false) {
    foreach ($data as $key => $value) {
        $data[$key] = trim($value);
    }
    
    // Process the CSV data here
}

fclose($handle);