Home > Article > Backend Development > How to send Excel exported by php as email_PHP tutorial
How to send Excel exported by php as email
Now the functions of downloading excel after clicking and sending text emails have been implemented. How can we combine it and send the excel exported by php as an attachment? It would be perfect.
1. Generate excel:
header("Content-type:application/octet-stream");
header("Accept-Ranges:bytes");
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=".$filename.".xls");
header("Pragma: no-cache");
header("Expires: 0");
if (!empty($title)){
foreach ($title as $k => $v) {
$title[$k]=iconv("UTF-8", "GB2312",$v);
}
$title= implode("t", $title);
echo "$titlen";
}
if (!empty($data)){
foreach($data as $key=>$val){
foreach ($val as $ck => $cv) {
$data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
}
$data[$key]=implode("t", $data[$key]);
}
echo implode("n",$data);
}
2. Send email:
Used the phpmailer class library
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = '';
$mail->Host = $config['SMTP_HOST']; // SMTP server
$mail->Port = $config['SMTP_PORT']; // SMTP server port number
$mail->Username = $config['SMTP_USER']; // SMTP server username
$mail->Password = $config['SMTP_PASS']; // SMTP server password
$mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
$replyEmail = $config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL'];
$replyName = $config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME'];
$mail->AddReplyTo($replyEmail, $replyName);
$mail->Subject = $subject;
$mail->MsgHTML($body);
$mail->AddAddress($to, $name);
if(is_file($attachment)){ //Add attachment
$mail->AddAttachment($attachment);
}
return $mail->Send()
------Solution--------------------
Add
at line 7ob_start();
Add
after line 23$s = ob_get_flush();
file_put_contents($filename.".xls", $s);
$attachment = $filename.".xls";
Execute email sending
------Solution--------------------
You must have made a mistake somewhere, check carefully
What you actually output is a text file, which can be opened with Notepad
The functions and usage of the ob function are all in the manual
------Solution--------------------
Sigh! There is no path for exporting like that. How do you send it as an attachment??
Isn’t this a fantasy?
------Solution--------------------
To give you an idea, you can refer to the following:
First save the excel on the server, then get the path of the excel, and then send it as an attachment by email. If you don’t need the file anymore, then delete it and it will be OK