php实现静态博客
PHP实现静态博客的方法
使用文件系统存储内容
创建文章存储目录,例如posts,每篇文章以.md或.txt格式保存。PHP通过scandir()读取目录内容,使用file_get_contents()获取文件内容。
$postsDir = 'posts';
$posts = array_diff(scandir($postsDir), ['.', '..']);
foreach($posts as $post) {
$content = file_get_contents("$postsDir/$post");
}
解析Markdown内容
安装Parsedown等Markdown解析库:
composer require erusev/parsedown
使用示例:
require 'vendor/autoload.php';
$parsedown = new Parsedown();
echo $parsedown->text($markdownContent);
生成静态HTML页面
创建模板系统,将解析后的内容插入HTML模板:
$template = file_get_contents('templates/post.html');
$html = str_replace('{{content}}', $parsedContent, $template);
file_put_contents("output/$postSlug.html", $html);
实现路由系统
通过.htaccess实现伪静态路由:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?slug=$1 [L,QSA]
PHP处理逻辑:
$slug = $_GET['slug'] ?? 'home';
$filePath = "posts/$slug.md";
if(file_exists($filePath)) {
// 显示文章
}
添加元数据支持
在Markdown文件顶部添加YAML front matter:
---
title: 文章标题
date: 2023-01-01
---
解析元数据:
function parseMeta($content) {
if(preg_match('/^---\s*(.+?)\s*---/s', $content, $matches)) {
$meta = yaml_parse($matches[1]);
$content = str_replace($matches[0], '', $content);
return [$meta, $content];
}
return [null, $content];
}
实现分类和标签
在元数据中添加分类信息:
categories: [PHP, Web]
tags: [静态网站, 博客]
构建分类索引:
$categories = [];
foreach($posts as $post) {
if(isset($post['meta']['categories'])) {
foreach($post['meta']['categories'] as $cat) {
$categories[$cat][] = $post;
}
}
}
生成RSS订阅
创建RSS生成脚本:
header('Content-Type: application/rss+xml');
$rss = new SimpleXMLElement('<rss version="2.0"/>');
$channel = $rss->addChild('channel');
$channel->addChild('title', '博客标题');
foreach($posts as $post) {
$item = $channel->addChild('item');
$item->addChild('title', $post['meta']['title']);
}
echo $rss->asXML();
部署到服务器
将生成的静态文件上传到任何Web服务器,或使用GitHub Pages等静态托管服务。对于动态部分,确保服务器支持PHP。
性能优化建议
- 使用OPcache加速PHP执行
- 实现缓存机制,避免重复解析
- 对静态资源启用浏览器缓存
- 使用CDN分发静态文件
这种实现方式结合了静态网站的快速性和PHP的动态处理能力,适合中小型博客项目。对于更复杂的需求,可以考虑基于现有框架如Laravel构建。







