PHP页面静态化

    xiaoxiao2021-03-25  51

    PHP静态化:就是使网站生成页面以静态HTML的形式展现在访客面前,PHP静态化分纯静态化和伪静态化,两者的区别在于PHP生成静态页面的处理机制不同。 真静态的3种方式: 1、利用PHP模板生成静态页面 PHP模板实现静态化非常方便,比如安装和使用PHP Smarty实现网站静态化。 2、使用PHP文件读写功能生成静态页面

    <? $out1 = "<html><head><title>PHP网站静态化教程</title></head> <body>欢迎访问PHP网站开发教程网www.leapsoul.cn,本文主要介绍PHP网站页面静态化的方法 </body></html>"; $fp = fopen("leapsoulcn.html","w"); if(!$fp) { echo "System Error"; exit(); } else { fwrite($fp,$out1); fclose($fp); echo "Success"; } ?>

    还有一种用file_put_contents,和fwrite效果差不多

    <? //基于Yii框架为例// $template = 'D:wamp/www/template/index.php'; $content = $this->renderInternal( $template, array( 'param1'=>'变量1','param2'=>'变量2'), true );//$param1和param2是要传入模板里的变量 $htmlfile = 'D:wamp/www/template/index.php';//获取生成路径 if(!is_dir(dirname($htmlfile))) mkdir( dirname( $htmlfile ), 0755, true );//如果静态目录不存在,则创建 file_put_contents( $htmlfile,$content ); ?>

    3、使用PHP输出控制函数(Output Control)生成静态页面 输出控制函数(Output Control)也就是使用和控制缓存来生成静态HTML页面,,也会使用到PHP文件读写函数

    <? ob_start(); echo "<html>". "<head>". "<title>PHP网站静态化教程</title>". "</head>". "<body>欢迎访问PHP网站开发教程网www.leapsoul.cn,本文主要介绍PHP网站页面静态化的方法</body>". "</html>"; $out1 = ob_get_contents(); ob_end_clean(); $fp = fopen("leapsoulcn.html","w"); if(!$fp) { echo "System Error"; exit(); } else { fwrite($fp,$out1); fclose($fp); echo "Success"; } ?>

    注释:PHP输出控制函数(Output Control)生成静态页面的思路: 首先开启缓存,然后输出了HTML内容(你也可以通过include将HTML内容以文件形式包含进来),之后获取缓存中的内容,清空缓存后通过PHP文件读写函数将缓存内容写入到静态HTML页面文件中。 过程需要使用三个函数:ob_start()、ob_get_contents()、ob_end_clean()。 (1)ob_start函数一般主要是用来开启缓存,注意使用ob_start之前不能有任何输出,如空格、字符等。

    (2)ob_get_contents函数主要用来获取缓存中的内容以字符串形式返回,注意此函数必须在ob_end_clean函数之前调用,否则获取不到缓存内容。

    (2)ob_end_clean函数主要是清空缓存中的内容并关闭缓存,成功则返回True,失败则返回False

    伪静态: 伪静态,就是url 重写

    'rules'=>array( '<controller:\w+>/<id:\d+>'=>'<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>', '<controller:\w+>/<action:\w+>'=>'<controller>/<action>', '<controller:\w+>/<action:\w+>'=>'/list/<action>/', //例如:news/sj/ '<action:\w+>'=>'/list/<action>/', //例如:news/ '<controller:\w+>/<action:\w+>/<id:\d+>.shtml'=>'/show/index/', //例如:news/sj/111.shtml '<action:\w+>/<id:\d+>.shtml'=>'/show/index/', //例如:video/222.shtml '<action:\w+>/list_<catid:\d+>_<page:\d+>.shtml'=>'/list/<action>/', //例如:video/list_25_5.shtml '<controller:\w+>/<action:\w+>/list_<catid:\d+>_<page:\d+>.shtml'=>'/list/<action>/', //例如:news/sj/list_25_5.shtml ),

    http://developer.51cto.com/art/201106/269132.htm

    转载请注明原文地址: https://ju.6miu.com/read-27361.html

    最新回复(0)