Home php教程 php手册 PHP 批量生成静态html

PHP 批量生成静态html

Jun 13, 2016 am 10:46 AM
html php information merchandise batch news generate net Information static page

众所周知,大部分网站的新闻资讯或商品信息都是静态页面。这样做的好处主要是为了: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


view plaincopy to clipboardprint? 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'; 

?> 
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


view plaincopy to clipboardprint? // 连接数据库  
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; 
    } 

?> 
// 连接数据库
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


view plaincopy to clipboardprint? // 操作 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()); 
        } 
    } 

?> 
// 操作 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


view plaincopy to clipboardprint? 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,替换完毕赋值给变量 $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('', $article[$item], $content); 
    } 
    return $content; 

?> 
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,替换完毕赋值给变量 $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('', $article[$item], $content);
 }
 return $content;
}
?>
        运行截图(Windows 的 DOS 为例)

运行完毕截图:


 运行2分钟左右就可以生成 9000多 html。

摘自 Lee.的专栏

 


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1237
24
Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles