How can PHP be used to export data to Excel upon clicking a button on a webpage?

To export data to Excel upon clicking a button on a webpage using PHP, you can create a PHP script that generates an Excel file with the data you want to export. When the button is clicked, this PHP script can be called using AJAX to generate and download the Excel file.

<?php
// Data to be exported to Excel
$data = array(
    array('Name', 'Age', 'Email'),
    array('John Doe', 30, 'john.doe@example.com'),
    array('Jane Smith', 25, 'jane.smith@example.com')
);

// Create Excel file
$filename = 'export_data_' . date('Ymd') . '.xls';
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");

$fp = fopen('php://output', 'w');
foreach ($data as $row) {
    fputcsv($fp, $row, "\t");
}
fclose($fp);
exit;
?>