PHP template parsing instance

Source: Internet
Author: User
Tags flock php foreach php template
This article mainly introduces the PHP template parsing class, which involves php's skills related to parsing template files and string processing, and has some reference value. For more information, see

This article mainly introduces the PHP template parsing class, which involves php's skills related to parsing template files and string processing, and has some reference value. For more information, see

This example describes the PHP template parsing class. Share it with you for your reference. The details are as follows:

<? Phpclass template {private $ vars = array (); private $ conf = ''; private $ tpl_name = 'index '; // If the template does not exist, the default index template private $ tpl_suffix = '.html 'of the current controller will be searched; // if the default suffix is not configured in CONFIG, private $ tpl_compile_suffix =' will be displayed '. tpl. php '; // compile the template path private $ template_tag_left =' <{'; // template left tag private $ template_tag_right ='}> '; // The right label of the template is private $ template_c = ''; // The compiling directory is private $ template_path =''; // The complete template path is private $ templat E_name = ''; // Template Name index.html // defines the element private $ tag_foreach = array ('from', 'item', 'key') for each template tag '); private $ tag_include = array ('file'); // currently, only the default template path public function _ construct ($ conf) {$ this-> conf = & $ conf; can be read; $ this-> template_c = $ this-> conf ['template _ config'] ['template _ C']; // compile the directory $ this-> _ tpl_suffix = $ this-> tpl_suffix ();} private function str_replace ($ search, $ replace, $ content) {if (empty ($ sear Ch) | empty ($ replace) | empty ($ content) return false; return str_replace ($ search, $ replace, $ content );} /*** preg_match_all * @ param $ pattern regular * @ param $ content * @ return array */private function preg_match_all ($ pattern, $ content) {if (empty ($ pattern) | empty ($ content) core: show_error ('template tag search failed! '); Preg_match_all (" http://www.jb51.net/ ". $ This-> template_tag_left. $ pattern. $ this-> template_tag_right. "/is", $ content, $ match); return $ match;}/*** template file suffix */public function tpl_suffix () {$ tpl_suffix = empty ($ this-> conf ['template _ config'] ['template _ suffix '])? $ This-> tpl_suffix: $ this-> conf ['template _ config'] ['template _ suffix ']; return $ tpl_suffix ;} /*** this does not explain * @ return */public function assign ($ key, $ value) {$ this-> vars [$ key] = $ value ;} /*** how to use the rendering page ** @ param * method 1 * $ this-> view-> display ('error', 'comm /'); * By default, it is directed to the following directory of the TPL template, so comm/is tpl/comm/error.html * usage method 2 * $ this-> view-> display ('errorfile '); * By default, it points to a fixed folder of the controller. * For example, if your domain name is, the correct path is tpl/admin/index. /Errorfile.html * @ return */public function display ($ filename = '', $ view_path ='') {$ tpl_path_arr = $ this-> get_tpl ($ filename, $ view_path ); // obtain the complete TPL path, transfer the path to the pointer, and name if (! $ Tpl_path_arr) core: show_error ($ filename. $ this-> _ tpl_suffix. 'template does not exist'); // compile start $ this-> view_path_param = $ view_path; // the template and directory passed by the user $ this-> compile ();} /*** compile controller * @ param * @ return */private function compile () {$ filepath = $ this-> template_path. $ this-> template_name; $ compile_dirpath = $ this-> check_temp_compile (); $ vars_template_c_name = str_replace ($ this-> _ tpl_suffix, '', $ this-> template_name ); $ incl Ude_file = $ this-> template_replace ($ this-> read_file ($ filepath), $ compile_dirpath, $ vars_template_c_name); // parse if ($ include_file) {$ this-> read_config () & $ config = $ this-> read_config (); extract ($ this-> vars, EXTR_SKIP); [url = home. php? Mod = space & uid = 48608] @ include [/url] $ include_file;}/*** read the current project configuration file */protected function read_config () {if (file_exists (SYSTEM_PATH. 'conf/config. php ') {@ include SYSTEM_PATH. 'conf/config. php '; return $ config;} return false ;} /*** parsing template syntax ** @ param $ str content * @ param $ compile_dirpath template compilation directory * @ param $ vars_template_c_name template compilation file name * @ return compiled PHP template file name */ private function template_replace ($ str, $ co Mpile_dirpath, $ vars_template_c_name) {if (empty ($ str) core: show_error ('the template content is blank! '); // Process the compilation header $ compile_path = $ compile_dirpath. $ vars_template_c_name. $ this-> tpl_compile_suffix; // compile the file if (is_file ($ compile_path) {// $ header_content = $ this-> get_compile_header ($ compile_path ); // $ compile_date = $ this-> get_compile_header_comment ($ header_content); $ tpl_filemtime = filemtime ($ this-> template_path. $ this-> template_name); $ compile_filemtime = filemtime ($ compile_path); // echo $ tpl_filemtime. '= '. date ('Y-m-d H: I: s', $ tpl_filemtime ).'
'; // Echo $ compile_filemtime. '= '. date ('Y-m-d H: I: s', $ compile_filemtime ); // if the file has expired, compile it again when the template tag has include and is modified. // <{include file = "public/left.html"}> when modifying the file in include, in non-DEBUG mode, if you do not change the main file, the file in the include is not re-compiled. I am considering whether to change it as well. I have not thought about it. For the time being, this is the case, therefore, you must enable the DEBUG = 1 mode in the development phase or modify the include file. A little wordy. I don't know whether to express it clearly. if ($ tpl_filemtime> $ compile_filemtime | DEBUG) {$ ret_file = $ this-> compile_file ($ vars_template_c_name, $ str, $ compile_dirpath );} else {$ ret_file = $ compile_path;} else {// The compilation file does not exist. Create it $ ret_file = $ this-> compile_file ($ vars_template_c_name, $ str, $ compile_dirpath );} return $ ret_file;}/*** template file subject * @ param string $ str content * @ return html */private function body_content ($ str) {// parse $ Str = $ this-> parse ($ str); $ header_comment = "Create On ##". time (). "| Compiled from ##". $ this-> template_path. $ this-> template_name; $ content = "<? If (! Defined ('is _ heartphp') exit ('Access Denied ');/* {$ header_comment} */?> \ R \ n $ str "; return $ content;}/*** start to parse the template tag * @ param $ content template content */private function parse ($ content) {// foreach $ content = $ this-> parse_foreach ($ content); // include $ content = $ this-> parse_include ($ content ); // if $ content = $ this-> parse_if ($ content); // elseif $ content = $ this-> parse_elseif ($ content ); // template tag common part $ content = $ this-> parse_comm ($ content); // convert to PHP code $ content = $ this-> parse_php ($ cont Ent); return $ content;}/*** echo <{$ config ['domain ']}> to <? Php echo $ config ['domain ']?> */Private function parse_echo ($ content) {}/*** convert to PHP * @ param $ content html template content * @ return html replaced HTML */private function parse_php ($ content) {if (empty ($ content) return false; $ content = preg_replace (" http://www.jb51.net/ ". $ This-> template_tag_left." (. + ?) ". $ This-> template_tag_right."/is "," <? Php $1?> ", $ Content); return $ content;}/*** if judgment statement * <{if empty ($ zhang)}> * zhang * <{elseif empty ($ liang)}> * liang * <{else}> * zhangliang * <{/if}> */private function parse_if ($ content) {if (empty ($ content) return false; // preg_match_all (" http://www.jb51.net/ ". $ This-> template_tag_left." if \ s + (.*?) ". $ This-> template_tag_right."/is ", $ content, $ match); $ match = $ this-> preg_match_all (" if \ s + (.*?) ", $ Content); if (! Isset ($ match [1]) |! Is_array ($ match [1]) return $ content; foreach ($ match [1] as $ k => $ v) {// $ s = preg_split ("/\ s +/is", $ v); // $ s = array_filter ($ s ); $ content = str_replace ($ match [0] [$ k], "<? Php if ({$ v}) {?> ", $ Content) ;}return $ content;} private function parse_elseif ($ content) {if (empty ($ content) return false; // preg_match_all (" http://www.jb51.net/ ". $ This-> template_tag_left." elseif \ s + (.*?) ". $ This-> template_tag_right."/is ", $ content, $ match); $ match = $ this-> preg_match_all (" elseif \ s + (.*?) ", $ Content); if (! Isset ($ match [1]) |! Is_array ($ match [1]) return $ content; foreach ($ match [1] as $ k => $ v) {// $ s = preg_split ("/\ s +/is", $ v); // $ s = array_filter ($ s ); $ content = str_replace ($ match [0] [$ k], "<? Php} elseif ({$ v}) {?> ", $ Content);} return $ content;}/*** the include tag is not updated in real time only when the subject file is updated, so if you want to include the file to take effect, Please modify the main file * record that you have time to develop a file for deletion of the template compilation file every time in DEBUG mode * usage <{include file = "www.phpddt.com"}> * @ param $ content template content * @ return html */private function parse_include ($ content) {if (empty ($ content) return false; // preg_match_all (" http://www.jb51.net/ ". $ This-> template_tag_left." include \ s + (.*?) ". $ This-> template_tag_right."/is ", $ content, $ match); $ match = $ this-> preg_match_all (" include \ s + (.*?) ", $ Content); if (! Isset ($ match [1]) |! Is_array ($ match [1]) return $ content; foreach ($ match [1] as $ match_key => $ match_value) {$ a = preg_split ("/\ s +/is", $ match_value); $ new_tag = array (); // analysis element foreach ($ a as $ t) {$ B = explode ('=', $ t); if (in_array ($ B [0], $ this-> tag_include) {if (! Empty ($ B [1]) {$ new_tag [$ B [0] = str_replace ("\" "," ", $ B [1]);} else {core: show_error ('template path does not exist! ') ;}} Extract ($ new_tag); // query the template file foreach ($ this-> conf ['view _ path'] as $ v) {$ conf_view_tpl = $ v. $ file; // include template file if (is_file ($ conf_view_tpl) {$ c = $ this-> read_file ($ conf_view_tpl ); $ inc_file = str_replace ($ this-> _ tpl_suffix, '', basename ($ file); $ this-> view_path_param = dirname ($ file ).' http://www.jb51.net/ '; $ Compile_dirpath = $ this-> check_temp_compile (); $ include_file = $ this-> template_replace ($ c, $ compile_dirpath, $ inc_file); // parse break ;} else {core: show_error ('template file does not exist. Please check the file carefully :'. $ conf_view_tpl) ;}}$ content = str_replace ($ match [0] [$ match_key], '<? Php include ("'. $ include_file.'")?> ', $ Content) ;}return $ content ;} /*** use method for parsing foreach * <{foreach from = $ lists item = value key = kk}> * @ param $ content template content * @ return html parsed content * /private function parse_foreach ($ content) {if (empty ($ content) return false; // preg_match_all (" http://www.jb51.net/ ". $ This-> template_tag_left." foreach \ s + (.*?) ". $ This-> template_tag_right."/is ", $ content, $ match); $ match = $ this-> preg_match_all (" foreach \ s + (.*?) ", $ Content); if (! Isset ($ match [1]) |! Is_array ($ match [1]) return $ content; foreach ($ match [1] as $ match_key => $ value) {$ split = preg_split ("/\ s +/is", $ value); $ split = array_filter ($ split); $ new_tag = array (); foreach ($ split as $ v) {$ a = explode ("=", $ v); if (in_array ($ a [0], $ this-> tag_foreach )) {// The filter tag does not exist here. Filter $ new_tag [$ a [0] = $ a [1] ;}$ key = ''; extract ($ new_tag ); $ key = ($ key )? '$'. $ Key. '=>': ''; $ s = '<? Php foreach ('. $ from.' as '. $ key.' $ '. $ item.') {?> '; $ Content = $ this-> str_replace ($ match [0] [$ match_key], $ s, $ content);} return $ content ;} /*** match end string */private function parse_comm ($ content) {$ search = array (" http://www.jb51.net/ ". $ This-> template_tag_left." \/foreach ". $ this-> template_tag_right."/is "," http://www.jb51.net/ ". $ This-> template_tag_left." \/if ". $ this-> template_tag_right."/is "," http://www.jb51.net/ ". $ This-> template_tag_left." else ". $ this-> template_tag_right."/is ",); $ replace = array (" <? Php }?> "," <? Php }?> "," <? Php} else {?> "); $ Content = preg_replace ($ search, $ replace, $ content); return $ content ;} /*** check if the compilation directory is not created, recursively create the directory * @ param string $ path file full path * @ return template content */private function check_temp_compile () {// $ paht = $ this-> template_c. $ tpl_path = ($ this-> view_path_param )? $ This-> view_path_param: $ this-> get_tpl_path (); $ all_tpl_apth = $ this-> template_c. $ tpl_path; if (! Is_dir ($ all_tpl_apth) {$ this-> create_dir ($ tpl_path);} return $ all_tpl_apth ;} /***** Read File * @ param string $ path complete file path * @ return template content */private function read_file ($ path) {// $ this-> check_file_limits ($ path, 'R'); if ($ r = @ fopen ($ path, 'R') = false) {core: show_error ('the template file has no read or execution permission. Check the file! ') ;}$ Content = fread ($ r, filesize ($ path); fclose ($ r); return $ content ;} /*** Write File ** @ param string $ filename file name * @ param string $ content template content * @ return file name */private function compile_file ($ filename, $ content, $ dir) {if (empty ($ filename) core: show_error ("{$ filename} Creation failed"); $ content = $ this-> body_content ($ content ); // file content operation // echo 'starts to compile ===='; $ f = $ dir. $ filename. $ this-> tpl_compile_suffix; // $ this-> check_file_limits ($ f, 'w'); if ($ fp = @ fopen ($ f, 'wb ')) === false) {core: show_error ($ f.'
Failed to compile the file. Check the file permission. ');} // enable flock ($ fp, LOCK_EX + LOCK_NB); fwrite ($ fp, $ content, strlen ($ content); flock ($ fp, LOCK_UN + LOCK_NB); fclose ($ fp); return $ f ;} /*** this file permission check function is temporarily obsolete * @ param [$ path] [path] * @ param [status] [w = write, r = read] */public function check_file_limits ($ path, $ status = 'rw ') {clearstatcache (); if (! Is_writable ($ path) & $ status = 'W') {core: show_error ("{$ path}
No write permission. Please check. ");} elseif (! Is_readable ($ path) & $ status = 'R') {core: show_error ("{$ path}
No read permission. Please check. ");} elseif ($ status = 'rw ') {// check wirte and readif (! Is_writable ($ path) |! Is_readable ($ path) {core: show_error ("{$ path}
No write or read permission. Please check ");}}} /*** read the first line of the compiled template and analyze it into an array * @ param string $ filepath * @ param number $ line number * @ return returns the string of the specified number of rows * // * private function get_compile_header ($ filepath, $ line = 0) {if ($ file_arr = @ file ($ filepath) === false) {core: show_error ($ filepath.'
Failed to read file. Please check file permission! ');} Return $ file_arr [0];} * // *** analyze the header comment date * @ param string $ cotnent the first line of the compiled file header * @ return returns the previous date * // * private function get_compile_header_comment ($ content) {preg_match ("/\/\*(. *?) \ * \ // ", $ Content, $ match); if (! Isset ($ match [1]) | empty ($ match [1]) core: show_error ('compilation error! '); $ Arr = explode (' | ', $ match [1]); $ arr_date = explode (' ##', $ arr [0]); return $ arr_date [1];} * // *** get the complete template path and return the existing file * @ param string $ filename file name * @ param string $ view_path template path * @ return */private function get_tpl ($ filename, $ view_path) {empty ($ filename) & $ filename = $ this-> tpl_name; // traverse the template path foreach ($ this-> conf ['view _ path'] as $ path) {if ($ view_path) {// find the file $ tpl_path = $ path from the tpl directory. $ view_p Ath; $ view_file_path = $ tpl_path. $ filename. $ this-> _ tpl_suffix;} else {// according to the directory, Controller, and method, start to find the file $ view_file_path = ($ tpl_path = $ this-> get_tpl_path ($ path ))? $ Tpl_path. $ filename. $ this-> _ tpl_suffix: exit (0);} if (is_file ($ view_file_path )) {// transfer the template path and Template Name To the pointer $ this-> template_path = $ tpl_path; // $ this-> template_name = $ filename. $ this-> _ tpl_suffix; return true;} else {core: show_error ($ filename. $ this-> _ tpl_suffix. 'template does not exist ');}}} /*** obtain the template path * @ param string $ path main directory * @ return url d and M splicing path */private function get_tpl_path ($ path = '') {core :: get_directory_name () & $ Path_arr [0] = core: get_directory_name (); core: get_controller_name () & $ path_arr [1] = core: get_controller_name (); (is_array ($ path_arr ))? $ Newpath = implode (' http://www.jb51.net/ ', $ Path_arr): core: show_error (' An error occurred while obtaining the template path! '); Return $ path. $ newpath .' http://www.jb51.net/ ';}/*** Create directory * @ param string $ path directory * @ return */private function create_dir ($ path, $ mode = 0777) {if (is_dir ($ path) return false; $ dir_arr = explode (' http://www.jb51.net/ ', $ Path); $ dir_arr = array_filter ($ dir_arr); $ allpath = ''; $ newdir = $ this-> template_c; foreach ($ dir_arr as $ dir) {$ allpath = $ newdir.' http://www.jb51.net/ '. $ Dir; if (! Is_dir ($ allpath) {$ newdir = $ allpath; if (! @ Mkdir ($ allpath, $ mode) {core: show_error ($ allpath .'
Failed to create directory. Please check whether you have the write permission! ');} Chmod ($ allpath, $ mode);} else {$ newdir = $ allpath;} return true;} public function _ destruct () {$ this-> vars = null; $ this-> view_path_param = null ;}}

I hope this article will help you with php programming.

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.