萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 產生 TXT/CSV/HTML 等格式檔案的類別實作

專案常需匯出報表為各種格式(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";
?>

擴充 CSV 格式範例

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} 方法動態派發,新增格式只需新增方法
  • 編碼處理:中文環境建議輸出 GBK 或 UTF-8+BOM,確保 Excel 開啟不亂碼
  • 資源管理:確實關閉檔案指標,大檔案建議分塊寫入
  • 目錄權限:執行前確認 $file_dir 可寫入
copyright © 萬盛學電腦網 all rights reserved