我来为你详细讲解如何用 PHP 写书,包括构建电子书、PDF、Word 等多种格式的方法。

📚 PHP 写书的完整方案
基础架构 - 构建图书内容
数据结构设计
<?php
// book.php - 图书数据结构
class Book {
private $title;
private $author;
private $chapters = [];
private $metadata = [];
public function __construct($title, $author) {
$this->title = $title;
$this->author = $author;
}
public function addChapter($title, $content) {
$this->chapters[] = [
'title' => $title,
'content' => $content
];
}
public function setMetadata($key, $value) {
$this->metadata[$key] = $value;
}
public function getBookData() {
return [
'title' => $this->title,
'author' => $this->author,
'chapters' => $this->chapters,
'metadata' => $this->metadata
];
}
}
?>
生成 PDF 格式
<?php
// generate_pdf.php - 使用 TCPDF 生成 PDF
require_once('tcpdf/tcpdf.php');
class PDFBookGenerator {
private $pdf;
public function __construct() {
$this->pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$this->setupDocument();
}
private function setupDocument() {
// 设置文档信息
$this->pdf->SetCreator(PDF_CREATOR);
$this->pdf->SetAuthor('Your Name');
$this->pdf->SetTitle('PHP Book Generator');
$this->pdf->SetSubject('Generated Book');
// 设置页边距
$this->pdf->SetMargins(20, 30, 20);
$this->pdf->SetHeaderMargin(10);
$this->pdf->SetFooterMargin(15);
// 自动分页
$this->pdf->SetAutoPageBreak(true, 25);
// 设置字体
$this->pdf->SetFont('helvetica', '', 11);
}
public function generate($bookData) {
$this->pdf->AddPage();
// 添加封面页
$this->addCoverPage($bookData);
// 添加目录
$this->addTableOfContents($bookData);
// 添加章节内容
foreach($bookData['chapters'] as $chapter) {
$this->addChapter($chapter);
}
// 输出 PDF
$this->pdf->Output($bookData['title'].'.pdf', 'D');
}
private function addCoverPage($bookData) {
// 设置封面样式
$this->pdf->SetFont('helvetica', 'B', 24);
$this->pdf->Cell(0, 20, $bookData['title'], 0, 1, 'C');
$this->pdf->SetFont('helvetica', '', 16);
$this->pdf->Cell(0, 10, $bookData['author'], 0, 1, 'C');
// 添加出版信息
$this->pdf->Ln(20);
$this->pdf->SetFont('helvetica', '', 12);
$this->pdf->Write(0, "Copyright © 2024");
}
private function addChapter($chapter) {
$this->pdf->AddPage();
// 章节标题
$this->pdf->SetFont('helvetica', 'B', 18);
$this->pdf->Write(0, $chapter['title']);
$this->pdf->Ln(10);
// 章节内容
$this->pdf->SetFont('helvetica', '', 11);
$this->pdf->WriteHTML($this->formatContent($chapter['content']));
}
private function formatContent($content) {
return nl2br(htmlspecialchars($content));
}
}
?>
生成 EPUB 格式
<?php
// generate_epub.php - 生成 EPUB 电子书
class EPUBBookGenerator {
private $bookData;
private $tempDir;
public function __construct() {
$this->tempDir = sys_get_temp_dir().'/epub_'.uniqid();
mkdir($this->tempDir, 0777, true);
}
public function generate($bookData) {
$this->bookData = $bookData;
// 创建 EPUB 目录结构
$this->createDirectoryStructure();
// 生成必要文件
$this->generateMimetype();
$this->generateContainer();
$this->generateOPF();
$this->generateNCX();
$this->generateChapterFiles();
// 创建 ZIP 压缩文件
$this->createEPUBFile();
}
private function createDirectoryStructure() {
$dirs = [
'META-INF',
'OEBPS/Text',
'OEBPS/Styles'
];
foreach($dirs as $dir) {
if(!file_exists($this->tempDir.'/'.$dir)) {
mkdir($this->tempDir.'/'.$dir, 0777, true);
}
}
}
private function generateMimetype() {
file_put_contents($this->tempDir.'/mimetype', 'application/epub+zip');
}
private function generateContainer() {
$content = '<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="OEBPS/content.opf"
media-type="application/oebps-package+xml"/>
</rootfiles>
</container>';
file_put_contents($this->tempDir.'/META-INF/container.xml', $content);
}
private function generateOPF() {
$metadata = $this->bookData['metadata'];
$content = '<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:title>'.$this->bookData['title'].'</dc:title>
<dc:creator>'.$this->bookData['author'].'</dc:creator>
<dc:language>zh-CN</dc:language>
<meta property="dcterms:modified">2024-01-01T00:00:00Z</meta>
</metadata>
<manifest>
<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>
<item id="styles" href="Styles/style.css" media-type="text/css"/>
<!-- 添加章节 -->
';
// 添加章节文件
$chapterCount = count($this->bookData['chapters']);
for($i = 0; $i < $chapterCount; $i++) {
$content .= '<item id="chapter'.$i.'" href="Text/chapter'.$i.'.xhtml" media-type="application/xhtml+xml"/>';
}
$content .= '</manifest>
<spine toc="ncx">';
// 添加 spine 顺序
for($i = 0; $i < $chapterCount; $i++) {
$content .= '<itemref idref="chapter'.$i.'"/>';
}
$content .= '</spine>
</package>';
file_put_contents($this->tempDir.'/OEBPS/content.opf', $content);
}
private function generateChapterFiles() {
$cssContent = 'body { font-family: serif; }
p { margin: 0.5em 0; }';
file_put_contents($this->tempDir.'/OEBPS/Styles/style.css', $cssContent);
// 生成章节 XHTML 文件
foreach($this->bookData['chapters'] as $index => $chapter) {
$content = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>'.$chapter['title'].'</title>
<link rel="stylesheet" href="../Styles/style.css"/>
</head>
<body>
<h1>'.$chapter['title'].'</h1>
<div>'.
nl2br(htmlspecialchars($chapter['content']))
.'</div>
</body>
</html>';
file_put_contents($this->tempDir.'/OEBPS/Text/chapter'.$index.'.xhtml', $content);
}
}
private function createEPUBFile() {
$zip = new ZipArchive();
$epubFile = $this->bookData['title'].'.epub';
if($zip->open($epubFile, ZipArchive::CREATE) === true) {
// 添加所有文件到 ZIP
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($this->tempDir)
);
foreach($files as $file) {
if(!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($this->tempDir)+1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
}
// 清理临时目录
$this->cleanupTempDir();
}
}
?>
生成 Word 文档
<?php
// generate_word.php - 使用 PHPWord 生成 Word
require_once('vendor/autoload.php');
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Shared\Html;
class WordBookGenerator {
private $phpWord;
public function __construct() {
$this->phpWord = new PhpWord();
$this->setupDocument();
}
private function setupDocument() {
// 设置文档属性
$properties = $this->phpWord->getDocInfo();
$properties->setCreator('PHP Book Generator');
$properties->setTitle('Generated Book');
// 添加默认样式
$this->phpWord->addParagraphStyle('normal', [
'spaceAfter' => 200,
'lineHeight' => 1.5
]);
// 标题样式
$this->phpWord->addTitleStyle(1,
['size' => 18, 'color' => '000000'],
['spaceBefore' => 200, 'spaceAfter' => 200]
);
$this->phpWord->addTitleStyle(2,
['size' => 14, 'color' => '333333'],
['spaceBefore' => 150, 'spaceAfter' => 150]
);
}
public function generate($bookData) {
// 添加封面
$this->addCoverPage($bookData);
// 添加内容
foreach($bookData['chapters'] as $chapter) {
$this->addChapter($chapter);
}
// 保存文档
$filename = $bookData['title'].'.docx';
$objWriter = IOFactory::createWriter($this->phpWord, 'Word2007');
$objWriter->save($filename);
return $filename;
}
private function addCoverPage($bookData) {
$section = $this->phpWord->addSection();
// 书名
$section->addTitle($bookData['title'], 1);
// 作者
$section->addText($bookData['author']);
// 出版信息
$section->addTextBreak(2);
$section->addText('Copyright © 2024');
}
private function addChapter($chapter) {
$section = $this->phpWord->addSection();
// 章节标题
$section->addTitle($chapter['title'], 1);
// 章节内容
$paragraphs = explode("\n", $chapter['content']);
foreach($paragraphs as $paragraph) {
$section->addText($paragraph);
}
}
}
?>
命令行工具示例
<?php
// book_writer.php - 命令行接口
class BookWriterCLI {
public function run($argv) {
if(count($argv) < 3) {
echo "Usage: php book_writer.php [pdf|epub|word] [book_file]\n";
exit(1);
}
$format = $argv[1];
$bookFile = $argv[2];
// 加载书籍数据
$bookData = $this->loadBookData($bookFile);
switch($format) {
case 'pdf':
$generator = new PDFBookGenerator();
$generator->generate($bookData);
break;
case 'epub':
$generator = new EPUBBookGenerator();
$generator->generate($bookData);
break;
case 'word':
$generator = new WordBookGenerator();
$generator->generate($bookData);
break;
default:
echo "Unsupported format: $format\n";
exit(1);
}
echo "Book generated successfully!\n";
}
private function loadBookData($file) {
// 支持 JSON 或 PHP 数组格式
if(pathinfo($file, PATHINFO_EXTENSION) == 'json') {
$data = json_decode(file_get_contents($file), true);
} else {
$data = include($file);
}
// 创建 Book 对象
$book = new Book($data['title'], $data['author']);
if(isset($data['chapters'])) {
foreach($data['chapters'] as $chapter) {
$book->addChapter($chapter['title'], $chapter['content']);
}
}
if(isset($data['metadata'])) {
foreach($data['metadata'] as $key => $value) {
$book->setMetadata($key, $value);
}
}
return $book->getBookData();
}
}
// 示例书籍数据文件 (book.json)
$bookData = [ => 'PHP Programming Guide',
'author' => 'John Doe',
'chapters' => [
[
'title' => '第一章:PHP基础',
'content' => "PHP 是一种流行的开源脚本语言...
本章将介绍 PHP 的基础知识..."
],
[
'title' => '第二章:面向对象编程',
'content' => "面向对象编程是 PHP 中重要的编程范式..."
]
],
'metadata' => [
'isbn' => '978-1234567890',
'publisher' => 'Tech Press'
]
];
// 运行命令行工具
if(PHP_SAPI === 'cli') {
$cli = new BookWriterCLI();
$cli->run($argv);
}
?>
推荐依赖库
# 安装依赖包 composer require tecnickcom/tcpdf # PDF 生成 composer require phpoffice/phpword # Word 文档 composer require mpdf/mpdf # 另一种 PDF 方案
使用示例
<?php
// 使用示例
include 'book.php';
include 'generate_pdf.php';
include 'generate_epub.php';
include 'generate_word.php';
// 创建书籍
$book = new Book('PHP从入门到精通', '张三');
$book->addChapter('第一章', 'PHP基础内容...');
$book->addChapter('第二章', '面向对象编程...');
// 获取书籍数据
$bookData = $book->getBookData();
// 生成 PDF
$pdfGenerator = new PDFBookGenerator();
$pdfGenerator->generate($bookData);
// 生成 EPUB
$epubGenerator = new EPUBBookGenerator();
$epubGenerator->generate($bookData);
?>
这个方案提供了完整的 PHP 写书功能,你可以根据需求选择不同的格式输出,记得根据实际需要调整样式和功能!