php可以通過自帶函數preg_replace可以用數組批量替換,不過用正則表達式替換效率很低,用起來也不方便。具體參考php手冊。有需要的小伙伴可以參考下。
這段代碼演示了php如何通過自定義的模板頁面和自定義標簽生成靜態頁面。原理非常簡單,就是將模板頁面中的標簽替換成動態數據即可。希望能給你一定的啟發。
template.html 模板文件
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>{site_title} - sharejs.com</title>
- </head>
- <body>
- <iframe width="100%" height="1000px" scrolling="yes" frameborder="0" src="{site_url}" ></iframe>
- </body>
- </html>
test.php 動態文件
- <?php
- header('content-type:text/html; charset=utf-8');//防止生成的頁面亂碼
- $title = "PHP 動態生成靜態HTML頁面_腳本分享網"; //定義變量
- $url = "http://www.49028c.com";
- $temp_file = "temp.html"; //臨時文件,也可以是模板文件
- $dest_file = "dest_page.html"; //生成的目標頁面
- $fp = fopen($temp_file, "r"); //只讀打開模板
- $str = fread($fp, filesize($temp_file));//讀取模板中內容
- $str = str_replace("{penglig_site_title}", $title, $str);//替換內容
- $str = str_replace("{penglig_site_url}", $url, $str);//替換內容
- fclose($fp);
- $handle = fopen($dest_file, "w"); //寫入方式打開需要寫入的文件
- fwrite($handle, $str); //把剛才替換的內容寫進生成的HTML文件
- fclose($handle);//關閉打開的文件,釋放文件指針和相關的緩沖區
- echo "<script>alert('生成成功');window.location.href='".$dest_file."';</script>";
- ?>
以上所述就是本文的全部內容了,希望大家能夠喜歡。
新聞熱點
疑難解答