What are common pitfalls when reading and outputting CSV files in PHP?

Common pitfalls when reading and outputting CSV files in PHP include not handling special characters properly, not properly handling empty fields, and not checking for errors during file operations. To solve these issues, it is important to use functions like fgetcsv() and fputcsv() which handle special characters and empty fields automatically, and to check for errors using functions like feof() and ferror().

// Reading a CSV file
$file = fopen('data.csv', 'r');
if ($file) {
    while (($data = fgetcsv($file)) !== false) {
        // Process the data
    }
    fclose($file);
} else {
    echo "Error opening file.";
}

// Writing to a CSV file
$data = array(
    array('John', 'Doe', 30),
    array('Jane', 'Smith', 25)
);

$file = fopen('output.csv', 'w');
if ($file) {
    foreach ($data as $row) {
        fputcsv($file, $row);
    }
    fclose($file);
} else {
    echo "Error opening file.";
}