PHP bulk Generation static html_php tutorial

Source: Internet
Author: User
Tags dsn rtrim
As we all know, most of the Web site news or product information are static pages. The advantages of this is mainly to: 1, speed up access, avoid excessive operation of the database; 2, SEO optimization, easy search engine included.

This example starts with a static page scheme for the CMS system and shows the bulk generation of static HTML functionality.

Note: This program can only be run under Windows DOS or Linux execution PHP commands.

This sample has 4 main files: config.inc.php (config file), Db.class.php (Database PDO Class), Model.class.php (PDO Database Operations Class), index.php (execute file)

config.inc.php


View Plaincopy to Clipboardprint? !--? 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 user name
define (' db_pwd ', ' 1715544 ');//Database password (please set your own according to the actual situation)
Funct Ion __autoload ($className) {
require_once root_path. '/includes/'. Ucfirst ($className). Class.php ';
}
?>
!--? 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 user name
define (' db_pwd ', ' 1715544 ');//Database password (please set your own according to the actual situation)
function __autoload ($className) {
require_once root_path. '/includes/'. Ucfirst ($className). Class.php ';
}
?
Db.class.php


View Plaincopy to Clipboardprint? Connecting to a database
Class Db {
static public Function Getdb () {
try {
$pdo = new PDO (DB_DSN, Db_user, db_pwd);
$pdo->setattribute (Pdo::attr_persistent, true); To set a database connection as a persistent connection
$pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception); Set throw error
$pdo->setattribute (Pdo::attr_oracle_nulls, true); Set NULL to convert the string to SQL when null
$pdo->query (' SET NAMES utf8 '); Set Database encoding
} catch (Pdoexception $e) {
Exit (' Database connection error, error message: '. $e->getmessage ());
}
return $pdo;
}
}
?>
Connecting to a database
Class Db {
static public Function Getdb () {
try {
$pdo = new PDO (DB_DSN, Db_user, db_pwd);
$pdo->setattribute (Pdo::attr_persistent, true); To set a database connection as a persistent connection
$pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception); Set throw error
$pdo->setattribute (Pdo::attr_oracle_nulls, true); Set NULL to convert the string to SQL when null
$pdo->query (' SET NAMES utf8 '); Set Database encoding
} catch (Pdoexception $e) {
Exit (' Database connection error, error message: '. $e->getmessage ());
}
return $pdo;
}
}
?>
Model.class.php


View Plaincopy to Clipboardprint? Manipulating SQL
Class Model {
/**
* SQL additions and deletions, returns the number of rows affected
* @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;
}

/**
* Return all data, return Pdostatement object
* @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 ());
}
}
}
?>
Manipulating SQL
Class Model {
/**
* SQL additions and deletions, returns the number of rows affected
* @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;
}

/**
* Return all data, return Pdostatement object
* @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, ', '); Collection of ID numbers for all articles
$IDARR = Explode (', ', $idStr); Split array
The following program loops through the generation of static pages
foreach ($idArr as $articleId) {
$re = $m->getall ("Select Id,title,date,author,source,content from article WHERE id =". $articleId); $re for the content of each article, note: its type is: pdostatement
$article = Array (); $article as an array that holds the title, date, author, content, source for each post
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 directory for static page placement
if (!is_dir ($articlePath)) mkdir ($articlePath, 0777); Checks whether the directory exists, does not exist, and creates
$fileName = Root_path. '/article/'. $articleId. '. html '; $fileName generated static file name, format: article id.html (primary key ID cannot conflict)
$articleTemPath = Root_path. '/templates/article.html '; $articleTemPath Article template path
$articleContent = file_get_contents ($articleTemPath); Get content inside a template
Replace the variables set inside the template. That is, for example: replace the <{title}> in the template with the title read in the database, replace the assigned value to the variable $articleContent
$articleContent = GetArticle (Array_keys ($article), $articleContent, $article);
$resource = fopen ($fileName, ' w ');
File_put_contents ($fileName, $articleContent); Writing HTML files
}

/**
* GetArticle ($arr, $content, $article) Replace the template
* @param array $arr substitution variables
* @param string $content template content
* @param array $article each article content arrays, Format: Array (' title ' =>xx, ' Date ' =>xx, ' author ' =>xx, ' source ' =>xx, ' content ' = &GT;XX);
*/
function GetArticle ($arr, $content, $article) {
Loop Replace
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, ', '); Collection of ID numbers for all articles
$IDARR = Explode (', ', $idStr); Split array
The following program loops through the generation of static pages
foreach ($idArr as $articleId) {
$re = $m->getall ("Select Id,title,date,author,source,content from article WHERE id =". $articleId); $re for the content of each article, note: its type is: pdostatement
$article = Array (); $article as an array that holds the title, date, author, content, source for each post
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 directory for static page placement
if (!is_dir ($articlePath)) mkdir ($articlePath, 0777); Checks whether the directory exists, does not exist, and creates
$fileName = Root_path. '/article/'. $articleId. '. html '; $fileName generated static file name, format: article id.html (primary key ID cannot conflict)
$articleTemPath = Root_path. '/templates/article.html '; $articleTemPath Article template path
$articleContent = file_get_contents ($articleTemPath); Get content inside a template
Replace the variables set inside the template. That is, for example: replace the <{title}> in the template with the title read in the database, replace the assigned value to the variable $articleContent
$articleContent = GetArticle (Array_keys ($article), $articleContent, $article);
$resource = fopen ($fileName, ' w ');
File_put_contents ($fileName, $articleContent); Writing HTML files
}

/**
* GetArticle ($arr, $content, $article) Replace the template
* @param array $arr substitution variables
* @param string $content template content
* @param array $article each article content arrays, Format: Array (' title ' =>xx, ' Date ' =>xx, ' author ' =>xx, ' source ' =>xx, ' content ' = >XX);
*/
function GetArticle ($arr, $content, $article) {
Loop Replace
foreach ($arr as $item) {
$content = Str_replace (' <{'. $item. '} > ', $article [$item], $content);
}
return $content;
}
?>
Run (DOS for Windows for example)

Run Complete:


More than 9,000 HTML can be generated in about 2 minutes of operation.

Excerpt from Lee's column


http://www.bkjia.com/PHPjc/478451.html www.bkjia.com true http://www.bkjia.com/PHPjc/478451.html techarticle As we all know, most of the Web site news or product information are static pages. The advantages of this is mainly to: 1, speed up access, avoid excessive operation of the database; 2, S ...

  • 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.