首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 動態生成文字檔下載:從資料庫到檔案輸出完整實作

     編輯:PHP 相關知識

需求分析

後台管理新聞資料(標題、日期、作者、內容),前台提供「下載」按鈕,點擊後自動將指定期間(如一個月)的新聞彙整成文字檔或 Word 檔下載。

方案一:純文字檔(.txt)最簡單實作

<?php
// download_news.php
require_once 'db.php';

$month_ago = date('Y-m-d', strtotime('-1 month'));
$stmt = $pdo->prepare("SELECT title, date, author, content FROM news WHERE date >= ? ORDER BY date DESC");
$stmt->execute([$month_ago]);
$rows = $stmt->fetchAll();

$filename = 'news_export_' . date('Ymd') . '.txt';
header('Content-Type: text/plain; charset=utf-8');
header("Content-Disposition: attachment; filename=\"$filename\"");

foreach ($rows as $row) {
    echo "標題:{$row['title']}\n";
    echo "日期:{$row['date']}\n";
    echo "作者:{$row['author']}\n";
    echo "內容:{$row['content']}\n";
    echo str_repeat('-', 50) . "\n\n";
}
exit;

方案二:Word 檔(.docx)使用 PHPWord

  1. 安裝:composer require phpoffice/phpword
  2. 產生 .docx:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpWord\PhpWord;

$phpWord = new PhpWord();
$section = $phpWord->addSection();

foreach ($rows as $row) {
    $section->addText($row['title'], ['bold' => true, 'size' => 14]);
    $section->addText("日期:{$row['date']}  作者:{$row['author']}");
    $section->addText($row['content']);
    $section->addTextBreak(2);
}

$filename = 'news_export_' . date('Ymd') . '.docx';
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header("Content-Disposition: attachment; filename=\"$filename\"");
$phpWord->save('php://output');
exit;

方案三:直接讀取現有檔案下載(適用已生成靜態檔)

<?php
$filepath = '/data/exports/news_202312.txt';
if (file_exists($filepath) && is_readable($filepath)) {
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
    header('Content-Length: ' . filesize($filepath));
    readfile($filepath);
    exit;
}
echo '檔案不存在';

關鍵 Header 說明

Header用途
Content-Type告知瀏覽器 MIME 類型,application/force-download 強制下載
Content-Disposition: attachment; filename="..."彈出「另存新檔」對話框,指定預設檔名
Content-Length檔案大小,支援進度條與續傳
charset=utf-8確保中文不亂碼

常見問題

  • 輸出前有空白/換行:確保 <?php 前無任何輸出,或用 ob_clean() 清空緩衝區。
  • 大檔案記憶體不足:改用 readfile() 串流輸出,勿一次 file_get_contents() 讀入記憶體。
  • 中文檔名亂碼:依 RFC 5987 編碼 filename*=UTF-8''%E6%96%87%E4%BB%B6.txt,或僅用 ASCII 檔名。

結語

文字檔下載極簡單,Word 檔建議用 PHPWord 等成熟套件。核心在於正確設定 HTTP Header 並串流輸出,避免記憶體溢位。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved