php - PhpSpreadsheet 强制下载文件不起作用 - 格式错误
问题描述
问题:创建的(XLSX)文件被发送到电子邮件并且运行良好,但是当我使用这个脚本下载它时它没有打开,MS Excel 显示“无效的文件格式或扩展名”错误。
我写了一个脚本来强制从服务器下载一个excel文件,如果有的话$_GET
,如果没有的话,通过电子邮件发送。
$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。
推荐阅读
- google-sheets - 如何提取前 5 个总和值及其前 3 个总和原因?
- r - 如何在 R 中使用聚类分析来识别仅给定存在-不存在数据的植被群落?
- javascript - Passport:req.user 未定义,从未调用反序列化
- laravel - 我无法使用 Laravel-Livewire 在模态中显示数据
- cmake - ctest 报错“没有找到测试配置文件!”
- sql - 加入有问题的第 3 列的 3 列
- html - 如何在中间对齐表格单元格同时使用 flex 对齐内部的内容而没有额外的空间
- php - 嘿,如何从 laravel 中的 klaviyo php-sdk 在 laravel 中收集短信同意
- ios - XCode 不允许我打开任何文件夹。难道我做错了什么?
- opengl - SSBO 与 VBO 性能