阅读量:74
PHP中常用的导出数据的方法有:
- 使用header()函数设置Content-Disposition头信息,并输出数据到浏览器,如导出CSV文件:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');
echo "Name,Age\n";
echo "Alice,25\n";
echo "Bob,30\n";
- 使用fputcsv()函数将数据写入文件,然后提供下载链接:
$file = fopen('data.csv', 'w');
fputcsv($file, array('Name', 'Age'));
fputcsv($file, array('Alice', 25));
fputcsv($file, array('Bob', 30));
fclose($file);
echo 'Download CSV';
- 使用PHPExcel等第三方库生成Excel文件:
require 'PHPExcel.php';
$excel = new PHPExcel();
$excel->setActiveSheetIndex(0)
->setCellValue('A1', 'Name')
->setCellValue('B1', 'Age')
->setCellValue('A2', 'Alice')
->setCellValue('B2', 25)
->setCellValue('A3', 'Bob')
->setCellValue('B3', 30);
$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$writer->save('data.xlsx');
echo 'Download Excel';
这些方法可以根据需要选择合适的方式来导出数据。