In what scenarios is it recommended to use fputcsv() over other methods for writing data to a file in PHP?

fputcsv() is recommended when you need to write data to a CSV file in PHP. It automatically formats the data into comma-separated values and handles special characters properly. This function is especially useful when dealing with large datasets or when you need to ensure compatibility with other applications that read CSV files.

// Sample code using fputcsv() to write data to a CSV file
$data = [
    ['John Doe', 'johndoe@example.com', '555-1234'],
    ['Jane Smith', 'janesmith@example.com', '555-5678'],
    ['Bob Johnson', 'bjohnson@example.com', '555-9876']
];

$fp = fopen('data.csv', 'w');

foreach ($data as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);