---
title: "PHP 直接静态化和触发静态化"
author: "onestopweb"
date: "2018-01-26T17:23:31Z"
tags: []
categories: ["编程语言"]
slug: "php"
draft: false
lastmod: "2018-01-26T17:23:45Z"
id: 2409199
url: "https://onestopweb.iteye.com/blog/2409199"
---

```
<?php
header('Content-Type: text/html; charset=utf-8');
ob_start();//开启缓存 
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>直接纯静态化</title>
</head>
<body>
<p>阅谁问君诵，水落清香浮</p>
</body>
</html>
<?php 
//把生成的静态内容保存到index.html文件，而不是输出到浏览器
file_put_contents( 'index.html', ob_get_clean());
?>
```

 效果图：  
![](http://dl2.iteye.com/upload/attachment/0128/6944/d7e6fdfc-b3ef-3533-94c8-45a10d759fd3.png)  
 

```
<?php
header('Content-Type: text/html; charset=utf-8');
$file_name = 'index2.html';
//如果文件是存在并且最后修改时间小于设定时间 10s
if(file_exists($file_name) && (time() - filemtime($file_name) < 10)){
    //echo time().'<br>';//当前时间
    //echo filemtime( $file_name ).'<br>';//得到文件最后修改时间
    require_once($file_name);//引入文件
}else{
ob_start();
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>指定时间触发生成纯静态化</title>
</head>
<body>
<p>onestopweb.iteye.com</p>
</body>
</html>
<?php
    //输出到浏览器
    file_put_contents($file_name, ob_get_contents());
}
?>
```

 效果图：  
![](http://dl2.iteye.com/upload/attachment/0128/6946/2be03167-d8fc-3092-bf48-7e881688b97c.jpg)