Php + smarty batch generate static files using php + smary to simulate dedecms background?> "Update all documents. In particular, it is easy to write because it is tested on the local machine to see the implemented functions. Of course, I am also a novice php enthusiast. You are welcome to criticize and correct me.
Step 1: Download and install smarty
(1) my website root directory: localhost/php/
(2) php root directory:
Libs directory ?? Smarty library file;
Tpls directory ?? The cache Directory, configs Directory, templates directory, and templates_c directory for storing smarty;
Article directory ?? Put all static files generated during the stay here
Index. php file ?? Php program code. when the page is accessed, static files are automatically generated in batches.
Step 2: index. php code
Everything is simplified. here, from the dede_archives table of the database, only the content of the fields id and title are read.
SetTemplateDir ('. /tpls/templates/'); $ smarty-> setCompileDir ('. /tpls/templates_c/'); $ smarty-> setConfigDir ('. /tpls/configs/'); $ smarty-> setCacheDir ('. /tpls/cache ');/*** read content from the database **/$ art = array (); $ mysqli = new mysqli ("localhost", "root ", "123456", "dedecmsv57gbksp1"); if ($ mysqli-> error) {die ("database connection failed :". $ mysqli-> error);} $ mysqli-> query ('set names utf8'); $ query = "select id, title from dede_archives limit 0, 3 "; // simple test, so I only read 3 articles $ res = $ mysqli-> query ($ query ); while ($ row = $ res-> fetch_assoc () {$ art [] = $ row;} $ mysqli-> close (); /*** generate a static file cyclically **/for ($ I = 0, $ len = count ($ art); $ I <$ len; $ I ++) {$ smarty-> assign ("id", $ art [$ I] ['id']); $ smarty-> assign ("title ", $ art [$ I] ['title']); $ str = $ smarty-> fetch ("view.html "); // Obtain the content after the smarty tag is replaced in the template. // Generate a static file $ fp = fopen (". /article/views -". $ art [$ I] ['id']. ". html "," w "); fwrite ($ fp, $ str) ; Fclose ($ fp);} echo "static file generated successfully";?>
Step 3: Template File./tpls/templates/view.html
{$ Title}Article id: {$ id}
Article title: {$ title}
OK. Then, access the index. php page, that is, the static file is automatically generated under the./article/directory.