Home  >  Article  >  Backend Development  >  PHP tutorial static file generation

PHP tutorial static file generation

巴扎黑
巴扎黑Original
2017-08-10 15:39:251528browse

It’s the third week in the company. The team is building a shopping platform. In order to improve the access speed, the general website will have many static pages, so that the database only needs to be accessed once and the data will no longer be read. . But what I never expected was that the team leader gave me the task of generating static pages. Hahahaha, I always thought that generating static pages was a high-level thing. Why would he give it to me, a newbie? Come and do it? ! But if you leave it to me, just do it. Wouldn’t it be a shame if you postpone it? . . .

The first task is to use the omnipotent search engine to find various senior experience on the Internet. Later, after looking at it, I found that it is actually very simple and not so mysteriousPHP tutorial static file generationIt's nothing more than using PHP's file class, then writing a function to generate a file, and referencing the function where you need to generate a static file is OK.

First introduce your own FILE class:

<?php
/**
 * 文件处理类
 */
class Files
{
	private $resource = null; //文件资源句柄
	function __construct($fileName,$mode=&#39;r&#39;)
	{
		$dirName  = dirname($fileName);//文件路径
		$baseName = basename($fileName);//文件名

		//检查并创建文件夹
		self::mkdir($dirName);

		$this->resource = fopen($fileName,$mode.&#39;b&#39;);
		if($this->resource)
		{
			flock($this->resource,LOCK_EX);//进行锁定
		}
	}
//文件写入函数
public function write($content)
	{
		$worldsnum = fwrite($this->resource,$content);
		return is_bool($worldsnum) ? false : $worldsnum;
	}
}
Write a function to generate static files:

private function writeHtml($path,$content){
		if(! class_exists(&#39;Files&#39;)){
		$this -> load ->file(APPPATH.&#39;libraries/Files&#39;.EXT);//本人用的CI 框架,引入文件类这里要稍作改动
		$f  = new Files($path,&#39;w+&#39;);
		$res = $f->write($content);
		$f->save();
	}
Finally, when needed Where a static page is generated, the above function is called:

function crativehtml{
		$url = "PHP动态文件路径";
		$content = file_get_contents($url);//获取文件内容
        $this -> _writeFile($path.&#39;文件名.html&#39;,$content);
	}

In this way, a static file is generated. The last file can be written in multiple places to generate different static files. ,,,

Let me summarize after doing this: It’s not difficult if you know it, but it’s not difficult if it’s difficult~ Nothing in high-level code is unfathomable. Eh~hehehehe,,

The above is the detailed content of PHP tutorial static file generation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn