How can PHP be used to export data to an Excel file and automate the process of sending this file via email on a regular basis?

To export data to an Excel file using PHP, you can utilize libraries like PHPExcel or PHPSpreadsheet. After exporting the data to Excel, you can use PHP's mail function to send the file as an attachment via email. To automate this process on a regular basis, you can set up a cron job to run a PHP script at specified intervals.

<?php
// Export data to Excel file
// Code using PHPExcel or PHPSpreadsheet library

// Send Excel file via email
$to = 'recipient@example.com';
$subject = 'Data Export';
$message = 'Please find attached the data export file.';
$filename = 'data_export.xlsx';
$file = '/path/to/exported/file/' . $filename;
$attachment = chunk_split(base64_encode(file_get_contents($file)));

$boundary = md5(time());
$headers = "From: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";

$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message));
$body .= "--$boundary\r\n";
$body .= "Content-Type: application/vnd.ms-excel; name=\"$filename\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"$filename\"\r\n\r\n";
$body .= $attachment . "\r\n";
$body .= "--$boundary--";

// Send email
mail($to, $subject, $body, $headers);
?>