PHP batch generate static html

Source: Internet
Author: User
As we all know, most website news or product information is static pages. The main benefits of doing so are: 1. speed up access and avoid excessive database operations; 2. SEO optimization to facilitate search engine indexing. This example is based on the static page solution of the CMS system, and displays the batch... SyntaxHighlighter. all ();

As we all know, most website news or product information is static pages. The main benefits of doing so are: 1. speed up access and avoid excessive database operations; 2. SEO optimization to facilitate search engine indexing.

This example describes how to generate static html in batches based on the CMS static page solution.

Note: This program can only run in Windows DOS or Linux by executing the PHP command.

In this example, there are four files: config. inc. php (configuration file), Db. class. php (database PDO class), Model. class. php (PDO database operation class), index. php (execution file)

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 _); // ROOT directory
Define ('Db _ DSN ', 'MySQL: host = localhost; dbname = article'); // mysql PDO dsn
Define ('Db _ user', 'root'); // database username
Define ('Db _ pwd', '000000'); // database password (set as needed)
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 _); // ROOT directory
Define ('Db _ DSN ', 'MySQL: host = localhost; dbname = article'); // mysql PDO dsn
Define ('Db _ user', 'root'); // database username
Define ('Db _ pwd', '000000'); // database password (set as needed)
Function _ autoload ($ className ){
Require_once ROOT_PATH. '/includes/'. ucfirst ($ className). '. class. php ';
}
?>
Db. class. php


View plaincopy to clipboardprint? // Connect to the database
Class Db {
Static public function getDB (){
Try {
$ Pdo = new PDO (DB_DSN, DB_USER, DB_PWD );
$ Pdo-> setAttribute (PDO: ATTR_PERSISTENT, true); // Set the database connection to persistent connection.
$ Pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION); // sets the throw error
$ Pdo-> setAttribute (PDO: ATTR_ORACLE_NULLS, true); // you can change the string to NULL to the SQL NULL.
$ Pdo-> query ('set NAMES utf8'); // sets the database encoding.
} Catch (PDOException $ e ){
Exit ('database connection error, error message: '. $ e-> getMessage ());
}
Return $ pdo;
}
}
?>
// Connect to the database
Class Db {
Static public function getDB (){
Try {
$ Pdo = new PDO (DB_DSN, DB_USER, DB_PWD );
$ Pdo-> setAttribute (PDO: ATTR_PERSISTENT, true); // Set the database connection to persistent connection.
$ Pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION); // sets the throw error
$ Pdo-> setAttribute (PDO: ATTR_ORACLE_NULLS, true); // you can change the string to NULL to the SQL NULL.
$ Pdo-> query ('set NAMES utf8'); // sets the database encoding.
} Catch (PDOException $ e ){
Exit ('database connection error, error message: '. $ e-> getMessage ());
}
Return $ pdo;
}
}
?>
Model. class. php


View plaincopy to clipboardprint? // Operate SQL
Class Model {
/**
* The SQL addition, deletion, and modification operations return the affected number of rows.
* @ 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;
}

/**
* All data is returned, and the PDOStatement object is returned.
* @ 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 ());
}
}
}
?>
// Operate SQL
Class Model {
/**
* The SQL addition, deletion, and modification operations return the affected number of rows.
* @ 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;
}
 
/**
* All data is returned, and the PDOStatement object is returned.
* @ 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, ','); // The ID set of all articles
$ IdArr = explode (',', $ idStr); // split it into arrays.
// The following program cyclically generates a static page
Foreach ($ idArr as $ articleId ){
$ Re = $ m-> getAll ("SELECT id, title, date, author, source, content FROM article WHERE id = ". $ articleId); // $ re indicates the content of each article. note: its type is PDOStatement.
$ Article = array (); // $ article is an array that stores the title, date, author, content, and source of each article.
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 is the directory where the static page is placed.
If (! Is_dir ($ articlePath) mkdir ($ articlePath, 0777); // check whether the directory exists. if it does not exist, create
$ FileName = ROOT_PATH. '/article/'. $ articleId. '.html '; // static file name generated by $ fileName. Format: article id.html (primary key ID cannot conflict with each other)
$ ArticleTemPath = ROOT_PATH. '/templates/article.html'; // $ articleTemPath document template path
$ ArticleContent = file_get_contents ($ articleTemPath); // get the content in the template
// Replace the variables set in the template. For example, replace <{title}> in the template with the title read in the database, and assign the value to the variable $ articleContent.
$ ArticleContent = getArticle (array_keys ($ article), $ articleContent, $ article );
$ Resource = fopen ($ fileName, 'w ');
File_put_contents ($ fileName, $ articleContent); // write the HTML file
}
 
/**
* GetArticle ($ arr, $ content, $ article) replaces the template.
* @ Param array $ arr replace the variable array
* @ Param string $ content template content
* @ Param array $ article an array of the content of each article. Format: array ('title' => xx, 'date' => xx, 'author' => xx, 'Source' => xx, 'content' => xx );
*/
Function getArticle ($ arr, $ content, $ article ){
// Cyclic replacement
Foreach ($ arr as $ item ){
$ Content = str_replace ('<{'. $ item. '}>', $ 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, ','); // The ID set of all articles
$ IdArr = explode (',', $ idStr); // split it into arrays.
// The following program cyclically generates a static page
Foreach ($ idArr as $ articleId ){
$ Re = $ m-> getAll ("SELECT id, title, date, author, source, content FROM article WHERE id = ". $ articleId); // $ re indicates the content of each article. note: its type is PDOStatement.
$ Article = array (); // $ article is an array that stores the title, date, author, content, and source of each article.
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 is the directory where the static page is placed.
If (! Is_dir ($ articlePath) mkdir ($ articlePath, 0777); // check whether the directory exists. if it does not exist, create
$ FileName = ROOT_PATH. '/article/'. $ articleId. '.html '; // static file name generated by $ fileName. Format: article id.html (primary key ID cannot conflict with each other)
$ ArticleTemPath = ROOT_PATH. '/templates/article.html'; // $ articleTemPath document template path
$ ArticleContent = file_get_contents ($ articleTemPath); // get the content in the template
// Replace the variables set in the template. For example, replace <{title}> in the template with the title read in the database, and assign the value to the variable $ articleContent.
$ ArticleContent = getArticle (array_keys ($ article), $ articleContent, $ article );
$ Resource = fopen ($ fileName, 'w ');
File_put_contents ($ fileName, $ articleContent); // write the HTML file
}

/**
* GetArticle ($ arr, $ content, $ article) replaces the template.
* @ Param array $ arr replace the variable array
* @ Param string $ content template content
* @ Param array $ article an array of the content of each article. Format: array ('title' => xx, 'date' => xx, 'author' => xx, 'Source' => xx, 'content' => xx );
*/
Function getArticle ($ arr, $ content, $ article ){
// Cyclic replacement
Foreach ($ arr as $ item ){
$ Content = str_replace ('<{'. $ item. '}>', $ article [$ item], $ content );
}
Return $ content;
}
?>
Running (Windows DOS is used as an example)

Completed:


You can generate more than 9000 html files in about 2 minutes.

From Lee.'s column

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.