What potential errors can occur when writing data to a .csv file in PHP?

When writing data to a .csv file in PHP, potential errors can occur due to incorrect formatting of the data, improper handling of special characters, or issues with file permissions. To avoid these errors, it's important to properly format the data before writing it to the file and to use functions that handle special characters appropriately. Additionally, ensure that the file has the correct permissions set to allow writing.

// Example code snippet to write data to a .csv file with error handling

$data = array(
    array('John Doe', 'johndoe@example.com'),
    array('Jane Smith', 'janesmith@example.com')
);

$filename = 'data.csv';

if (($handle = fopen($filename, 'w')) !== false) {
    foreach ($data as $row) {
        fputcsv($handle, $row);
    }
    fclose($handle);
    echo 'Data written to ' . $filename;
} else {
    echo 'Error opening ' . $filename . ' for writing';
}