專案常需匯出報表為各種格式(TXT、CSV、HTML、PDF、Word)。本文提供一個可擴充的檔案產生器類別,以 TXT 格式為例展示核心架構,易於擴充支援其他格式。
<?php
/*************************************************
* Class: CreateFile
* Description: 產生不同類型檔案 (TXT, CSV, HTML, PDF, DOC)
* Author: fenghuo
* Date: 2013-11-12
************************************************/
class CreateFile {
public $file_dir; // 檔案儲存目錄
public $file_name; // 預設檔名
public $file_type; // 預設類型
public function __construct($file_dir) {
$this->file_dir = rtrim($file_dir, '/\\') . '/';
}
/**
* 產生檔案入口
* @param string $file_name 檔名
* @param string $file_type 類型 (txt, csv, html...)
* @param array $title 標題列陣列
* @param array $data 內容資料二維陣列
* @return bool|string
*/
public function create_file($file_name, $file_type, $title, $data) {
if (empty($data)) return false;
if (!empty($title) && count($title) !== count($data[0])) return false;
$file_name = $file_name ?: $this->file_name;
$file_type = $file_type ?: $this->file_type;
$method = 'mk_' . $file_type;
if (method_exists($this, $method)) {
$file_path = $this->file_dir . $file_name . '.' . $file_type;
return $this->$method($file_path, $title, $data);
}
return "不支援的格式: $file_type";
}
/**
* 產生 TXT 格式 (定寬欄位)
*/
public function mk_txt($file, $title, $data) {
$content = '';
// 寫入標題
if (!empty($title)) {
foreach ($title as $col) {
$content .= ' ' . mb_convert_encoding($col, 'GBK', 'UTF-8');
}
$content .= "\r\n";
}
// 寫入資料
foreach ($data as $row) {
foreach ($row as $col) {
$content .= ' ' . mb_convert_encoding($col, 'GBK', 'UTF-8');
}
$content .= "\r\n";
}
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
return true;
}
// 可擴充:mk_csv(), mk_html(), mk_pdf(), mk_doc()...
}
?>
<?php
require_once 'CreateFile.php';
$dir = 'E:/exports/';
$file_name = "member_report_" . date('Ymd');
$file_type = "txt";
$title = array("姓名", "性別", "年齡", "城市");
$data = [
array("張三", "男", 25, "北京"),
array("李四", "女", 28, "上海"),
array("王五", "男", 32, "廣州"),
];
$generator = new CreateFile($dir);
$result = $generator->create_file($file_name, $file_type, $title, $data);
echo $result === true ? "匯出成功: {$dir}{$file_name}.{$file_type}" : "匯出失敗: $result";
?>
public function mk_csv($file, $title, $data) {
$fp = fopen($file, 'w');
// 寫入 BOM 讓 Excel 正確識別 UTF-8
fwrite($fp, "\xEF\xBB\xBF");
if (!empty($title)) {
fputcsv($fp, $title);
}
foreach ($data as $row) {
fputcsv($fp, $row);
}
fclose($fp);
return true;
}
mk_{type} 方法動態派發,新增格式只需新增方法$file_dir 可寫入