What are some best practices for using PHP functions like fgetcsv() and fwrite() when working with CSV files?

When working with CSV files in PHP, it is important to use built-in functions like fgetcsv() to read data from a CSV file and fwrite() to write data to a CSV file. Best practices include properly handling file pointers, error checking, and closing files after use to prevent memory leaks or file corruption.

// Example of reading from a CSV file using fgetcsv()
$filename = 'data.csv';
$handle = fopen($filename, 'r');

if ($handle !== false) {
    while (($data = fgetcsv($handle)) !== false) {
        // Process data from CSV file
        print_r($data);
    }
    
    fclose($handle);
} else {
    echo 'Error opening file';
}

// Example of writing to a CSV file using fwrite()
$filename = 'output.csv';
$handle = fopen($filename, 'w');

if ($handle !== false) {
    $data = ['John', 'Doe', 'john.doe@example.com'];
    fputcsv($handle, $data);
    
    fclose($handle);
} else {
    echo 'Error opening file';
}