What are the potential pitfalls of formatting data with PHP for Excel export?

One potential pitfall of formatting data with PHP for Excel export is that special characters or formatting may not be handled correctly, leading to errors or unexpected behavior in the exported file. To avoid this, it is important to properly sanitize and format the data before exporting it to Excel.

// Example code snippet for sanitizing and formatting data before exporting to Excel
$data = array(
    array('Name', 'Age', 'Email'),
    array('John Doe', 30, 'john.doe@example.com'),
    array('Jane Smith', 25, 'jane.smith@example.com')
);

// Sanitize and format data
foreach ($data as $key => $row) {
    foreach ($row as $k => $value) {
        $data[$key][$k] = htmlspecialchars($value);
    }
}

// Export data to Excel
$filename = 'exported_data_' . date('Y-m-d') . '.xls';
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
foreach ($data as $row) {
    echo implode("\t", $row) . "\n";
}