Batch generation of static HTML in PHP (run PHP under command line) _php tips

Source: Internet
Author: User
Tags getmessage

As we all know, most of the website news or merchandise information are static pages. The advantage of this is mainly to: 1, speed up access, avoid too much operation of the database, 2, SEO optimization, easy to collect search engines.

This example focuses on the static page scheme of the CMS system, showing the batch generation of static HTML functionality.
Note: This program can only be run with PHP commands on Windows DOS or Linux.
This example has 4 files: config.inc.php (configuration file), Db.class.php (Database PDO Class), Model.class.php (PDO database Operation Class), index.php (execute file)
config.inc.php

Copy Code code as follows:

<?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 '); PDO DSN for MySQL
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

Copy Code code as follows:

<?php
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 the database connection as a persistent connection
$pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception); Set throw error
$pdo->setattribute (Pdo::attr_oracle_nulls, true); Sets NULL to be converted to SQL when the string is 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

Copy Code code as follows:

<?php
Manipulating SQL
Class Model {
/**
* SQL additions and deletions, returns the number of affected 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;
}

/**
* 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

Copy Code code as follows:

<?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, ', '); Collection of ID numbers for all articles
$IDARR = Explode (', ', $idStr); Split an array
The following program loops to generate a static page
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 is an array that holds the title, date, author, content, 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 a table of contents to be placed on a static page
if (!is_dir ($articlePath)) mkdir ($articlePath, 0777); Check whether the directory exists or not, create
$fileName = Root_path. '/article/'. $articleId. '. html '; $fileName generated static filename, 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 what's inside the template
Replace the variables that are 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); Write HTML file
}

/**
* Getarticle ($arr, $content, $article) to replace the template
* @param array $arr substitution variables
* @param string $content template contents
* @param array $article The contents of each article, in the form of Arrays: 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;
}
?>

Run screenshots (DOS of Windows for example)

Run Complete screenshot:



Run 2 minutes or so to generate more than 9,000 HTML.

A column reprinted from Lee, indicating the source!!!

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.