PHP 页面静态化处理,生成静态页面!
做SEO的都知道,最好是把我们的网站页面生成静态页面,好处就太多了。下面我们直接搞!
首先我们在一个公共的服务层,封装一个生成静态页面的方法
/**
 * 生成静态页面
 * @param string $filePath
 * @param string $htmlStr
 */
public static function generateStaticPage(string $filePath, string $htmlStr)
{
    switch ($filePath)
    {
        case "index" || "/":
            return file_put_contents('index.html',$htmlStr);
        default:
            //自定义页面
            $dir = iconv("UTF-8", "GBK", $filePath);
            $path = str_replace("/","\\",public_path($dir));
            if (!file_exists($path))
                mkdir($dir,0777,true);
            return file_put_contents('./'.$filePath.'/index.html',$htmlStr);
    }
}然后调用:
//生成静态页
$res = CommonService::generateStaticPage($routeMaps->route,$indexHtmlStr);
if (!empty($res) || $res != 0){
    dump("页面生成成功");
}
return view("index");这样就可以生成我们的网页了,但是有个问题,这种只是针对那种单页面,对于有数据渲染和功能交互的页面就不行了,所以我们要在进行View页面交互后生成静态页然后放入html中,如下:
下面以Laravel为例:
$news= News::get();
$string = view('news.news',compact("news"))->__toString();
file_put_contents("index.html", $string);现在基本上就差不多了。



还没有评论,快来发表第一个评论吧