众所周知,大部分网站的新闻资讯或商品信息都是静态页面。这样做的好处主要是为了:1、加快访问速度,避免过多的操作数据库;2、SEO优化,便于搜索引擎收录。
本示例围绕 CMS 系统的静态页面方案出发,展示批量生成静态 html 功能。 注:本文程序只能在 Windows 的 DOS 或 Linux 下执行 PHP 命令来运行。 本示例主要有4个文件:config.inc.php(配置文件)、Db.class.php(数据库 PDO 类)、Model.class.php(PDO数据库操作类)、index.php(执行文件) config.inc.php- <?php
- header('Content-Type:text/html;Charset=utf-8');
- date_default_timezone_set('PRC');
- define('ROOT_PATH', dirname(__FILE__)); // 根目录
- define('DB_DSN', 'mysql:host=localhost;dbname=article'); // MySQL 的 PDO dsn
- define('DB_USER', 'root'); // 数据库用户名
- define('DB_PWD', '1715544'); // 数据库密码(请您根据实际情况自行设定)
- function __autoload($className) {
- require_once ROOT_PATH . '/includes/'. ucfirst($className) .'.class.php';
- }
- ?>
Db.class.php
- <?php
- // 连接数据库
- class Db {
- static public function getDB() {
- try {
- $pdo = new PDO(DB_DSN, DB_USER, DB_PWD);
- $pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接
- $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置抛出错误
- $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 设置当字符串为空转换为 SQL 的 NULL
- $pdo->query('SET NAMES utf8'); // 设置数据库编码
- } catch (PDOException $e) {
- exit('数据库连接错误,错误信息:'. $e->getMessage());
- }
- return $pdo;
- }
- }
- ?>
Model.class.php
- <?php
- // 操作 SQL
- class Model {
- /**
- * SQL 增删改操作,返回受影响的行数
- * @param string $sql
- * @return int
- */
- public function aud($sql) {
- try {
- $pdo = Db::getDB();
- $row = $pdo->exec($sql);
- } catch (PDOException $e) {
- exit($e->getMessage());
- }
- return $row;
- }
- /**
- * 返回全部数据,返回 PDOStatement 对象
- * @param string $sql
- * @return PDOStatement
- */
- public function getAll($sql) {
- try {
- $pdo = Db::getDB();
- $result = $pdo->query($sql);
- return $result;
- } catch (PDOException $e) {
- exit($e->getMessage());
- }
- }
- }
- ?>
index.php
- <?php
- require_once './config.inc.php';
- $m = new Model();
- $ids = $m->getAll("select id FROM article ORDER BY id ASC");
- foreach ($ids as $rowIdArr) {
- $idStr .= $rowIdArr['id'].',';
- }
- $idStr = rtrim($idStr, ','); // 所有文章的 ID 号集合
- $idArr = explode(',', $idStr); // 分割成数组
- // 下面的程序循环生成静态页面
- foreach ($idArr as $articleId) {
- $re = $m->getAll("select id,title,date,author,source,content FROM article WHERE id =". $articleId); // $re 为每篇文章的内容,注意:其类型为:PDOStatement
- $article = array(); // $article 为一个数组,保存每篇文章的title、date、author、content、source
- foreach ($re as $r) {
- $article = array(
- 'title'=>$r['title'],
- 'date'=>$r['date'],
- 'author'=>$r['author'],
- 'source'=>$r['source'],
- 'content'=>$r['content']
- );
- }
- $articlePath = ROOT_PATH. '/article'; // $articlePath 为静态页面放置的目录
- if (!is_dir($articlePath)) mkdir($articlePath, 0777); // 检查目录是否存在,不存在则创建
- $fileName = ROOT_PATH . '/article/' . $articleId . '.html'; // $fileName 生成的静态文件名,格式:文章ID.html(主键ID不可能冲突)
- $articleTemPath = ROOT_PATH . '/templates/article.html'; // $articleTemPath 文章模板路径
- $articleContent = file_get_contents($articleTemPath); // 获取模板里面的内容
- // 对模板里面设置的变量进行替换。即比如:把模板里面的 <{title}> 替换成数据库里读取的 title,替换完毕赋值给变量 $articleContent
- $articleContent = getArticle(array_keys($article), $articleContent, $article);
- $resource = fopen($fileName, 'w');
- file_put_contents($fileName, $articleContent); // 写入 HTML 文件
- }
- /**
- * getArticle($arr, $content, $article) 对模板进行替换操作
- * @param array $arr 替换变量数组
- * @param string $content 模板内容
- * @param array $article 每篇文章内容数组,格式:array('title'=>xx, 'date'=>xx, 'author'=>xx, 'source'=>xx, 'content'=>xx);
- */
- function getArticle($arr, $content, $article) {
- // 循环替换
- foreach ($arr as $item) {
- $content = str_replace('<{'. $item .'}>', $article[$item], $content);
- }
- return $content;
- }
- ?>
本文转载自