Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php如何导出数据

作者:不,完美   发布日期:2025-05-19   浏览:474

在PHP中,可以使用以下方法导出数据:

  1. 导出为CSV文件:使用fputcsv()函数将数据写入CSV文件。
// 创建CSV文件
$filename = 'data.csv';
$file = fopen($filename, 'w');

// 写入表头
$header = array('姓名', '年龄', '邮箱');
fputcsv($file, $header);

// 写入数据
$data = array(
    array('John Doe', 30, 'john@example.com'),
    array('Jane Smith', 25, 'jane@example.com'),
    array('Tom Brown', 35, 'tom@example.com')
);

foreach ($data as $row) {
    fputcsv($file, $row);
}

// 关闭文件
fclose($file);

// 下载文件
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filename);
  1. 导出为Excel文件:使用第三方库,如PHPExcel或PhpSpreadsheet。
// 使用PhpSpreadsheet库导出Excel文件
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// 创建Excel对象
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// 设置表头
$sheet->setCellValue('A1', '姓名');
$sheet->setCellValue('B1', '年龄');
$sheet->setCellValue('C1', '邮箱');

// 设置数据
$data = array(
    array('John Doe', 30, 'john@example.com'),
    array('Jane Smith', 25, 'jane@example.com'),
    array('Tom Brown', 35, 'tom@example.com')
);

$row = 2;
foreach ($data as $item) {
    $sheet->setCellValue('A' . $row, $item[0]);
    $sheet->setCellValue('B' . $row, $item[1]);
    $sheet->setCellValue('C' . $row, $item[2]);
    $row++;
}

// 导出Excel文件
$writer = new Xlsx($spreadsheet);
$filename = 'data.xlsx';
$writer->save($filename);

// 下载文件
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filename);

这些方法可以根据需要进行调整和扩展,以满足具体的导出数据需求。

上一篇:php 获得某个月的某天(php获取今天日期)

下一篇:php创建目录并赋值权限?(php创建目录并赋值权限怎么设置)

大家都在看

php session用法

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

php ||

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站