[英]PhpSpreadsheet force download file not working - bad format
问题 :创建的(XLSX)文件发送到电子邮件并可以正常工作,但是当我使用此脚本下载文件时无法打开,MS Excel显示“无效的文件格式或扩展名”错误。
我编写了一个脚本,如果有$_GET
,则强制从服务器下载excel文件,如果没有,则通过电子邮件发送。
$writer = new Xlsx( $spreadsheet );
$writer->save( 'file.xlsx' );
$file_path = PATH_TO_FILE; // for example purposes
if( isset( $_GET['action'] ) && 'download' == $_GET['action'] ) {
// force download file
if( file_exists( $file_path ) ) {
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename=" ' . basename( $file_path ) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize( $file_path ) );
flush(); // Flush system output buffer
readfile( $file_path );
exit;
}
}
else {
// send email
$to = 'example@example';
$subject = 'subject';
$body = 'body ' . date( 'd-m-Y' );
$headers = array(
'Content-Type: text/html; charset=UTF-8',
'From: John Doe <info@example.com>',
);
$attachment = array( $file_path );
$result = wp_mail( $to, $subject, $body, $headers, $attachment );
if( !$result ) {
error_log( '$result: ' . print_r( $result, true ) );
}
}
* PATH_TO_FILE
指向实际文件
知道为什么文件下载脚本会生成错误的Excel文件吗?
谢谢!
感谢@ino的技巧,我设法解决了这个问题。
您必须确保 PHP标记之前没有HTML / CSS / JS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.