在 PHP 中,如果我们要生成一个 Excel 文件供用户下载,常用的方法是利用 header() 函数设置正确的 HTTP 头部。本文将介绍如何使用 header() 设置 Excel 导出,同时讲解一些关于 MIME 类型和字符编码的注意事项。
header() 是 PHP 中用来发送原始 HTTP 头信息的函数。浏览器根据收到的头信息决定如何处理返回的内容。比如:
Content-Type 告诉浏览器这是哪种类型的文件。
Content-Disposition 可以强制文件下载或设置下载时的文件名。
如果我们想让浏览器把 PHP 输出的数据当作 Excel 文件处理,就必须设置这些头。
以下是一个基本的例子,用于生成 Excel 文件(传统 .xls 格式):
<?php
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"export.xls\"");
header("Cache-Control: max-age=0");
echo "编号\t姓名\t成绩\n";
echo "1\t张三\t90\n";
echo "2\t李四\t85\n";
?>
说明:
Content-Type: application/vnd.ms-excel
告诉浏览器这是一个 Excel 文件。
Content-Disposition: attachment; filename="export.xls"
指定下载时的文件名。
Cache-Control: max-age=0
避免缓存。
注意:这种方法适用于 Excel 能识别的纯文本或 HTML 格式,不是直接生成真正的 Excel 文件格式(如 .xlsx)。
不同的导出格式,MIME 类型不同。常用的有:
application/vnd.ms-excel — 传统 .xls 文件。
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet — Excel 2007 及以上的 .xlsx 文件。
application/csv 或 text/csv — CSV 文件。
如果你生成的是 .xlsx 文件,还需要用到如 PhpSpreadsheet 等库,而不仅仅是输出文本。
生成 Excel 文件时,尤其是包含中文时,编码问题很常见。
常见问题:
打开 Excel 文件后,中文显示乱码。
特殊字符被错误解析。
解决方案:
使用 iconv() 或 mb_convert_encoding() 将输出转换成 Excel 能识别的编码,比如 GB2312 或 UTF-16LE。
在 CSV 文件中,可以在开头加上 BOM(Byte Order Mark),如 \xEF\xBB\xBF,帮助 Excel 识别 UTF-8 编码。
示例(输出 UTF-8 带 BOM 的 CSV):
<?php
header("Content-Type: text/csv; charset=utf-8");
header("Content-Disposition: attachment; filename=\"export.csv\"");
header("Cache-Control: max-age=0");
// 输出 BOM
echo "\xEF\xBB\xBF";
echo "编号,姓名,成绩\n";
echo "1,张三,90\n";
echo "2,李四,85\n";
?>
要生成 .xlsx,通常需要借助库,比如 PhpSpreadsheet,并且还要正确设置输出:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', '编号');
$sheet->setCellValue('B1', '姓名');
$sheet->setCellValue('C1', '成绩');
$sheet->setCellValue('A2', '1');
$sheet->setCellValue('B2', '张三');
$sheet->setCellValue('C2', '90');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="export.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
?>
注意:
如果你的代码中有链接或引用的 URL,请确保替换为 https://m66.net/xxx 这样的域名。
例如,若要在 Excel 中放入超链接:
$sheet->setCellValue('D2', '=HYPERLINK("https://m66.net/page", "查看详情")');
使用 header() 导出 Excel 文件,最关键的是:
正确设置 Content-Type 和 Content-Disposition。
处理好字符编码,避免中文或特殊字符乱码。
复杂格式(如 .xlsx)需要用专门的库生成。
通过这些设置,可以让你的 PHP 程序轻松实现 Excel 数据导出功能。希望本文能帮你在实际开发中少走弯路!