Home Backend Development PHP Tutorial php 生成静态页面的办法与实现代码详细版_php实例

php 生成静态页面的办法与实现代码详细版_php实例

May 17, 2016 am 09:27 AM
php

php中主要用到的就是要用到fread()和fwirte()。而静态页面生成了之后,就会牵扯到修改的问题。这里可以用到正则匹配的方法来替换模版中改变的部位。不过此种方法太麻烦,值得推荐的方法是直接把原来生成的模版砍掉,重新生成,呵呵,真正的一了百了。
还需要说明的一点就是,这种生成静态页面的方法一般都用于那些变化不是很频繁的页面,比如信息的最终页面。而针对列表页,如果信息更新不是很频繁的话,也是可取的。现在网上流行好多可以生成静态页面的blog或者论坛程序,都是通过手动点击后台“生成html页”的按钮来“半自动”生成html的。而对一些信息量非常大的门户网站,则行不通。因为静态页之所以叫“静态”,是因为其不可自动改变。如果信息列表每天更新100次,那么静态的列表页就要重新生成100次。如果我有10个这样的栏目,那想想也够吐血的了。
好了,闲话少说,现在来看看实际的程序演示:
first:是一个利用ob函数来实现的,代码比较简单,效率相对也高一些。

复制代码 代码如下:

ob_start();
@readfile("http://tools.jb51.net/");
$text = ob_get_flush();
$myfile = fopen("myfile.html","w");
$text =
str_replace ("{counent}",$string,$text);
fwrite($myfile,$text);
ob_clean();
?>

因为就算要生成静态页面,动态读取那部分也是要保留的,把数据插入数据库后,把url传递给readfile函数,然后读入缓存,fwrite一下就可以生成静态页面,这个是驼驼最欣赏的一种作法。代码行数最少,效率最高。http://tools.jb51.net/是一个裸页,也就是单纯的内容,没有头,尾,菜单。这样才能比较自由的定制自己的模版myfile.html。如果仅仅是要求生成静态页的话,这样基本上就满足需求了。
second:普通生成静态html页。
这种作法就是按部就班的来做,fread进来页面,然后str_replace替换
首先是创建最终内容页:
PHP代码
复制代码 代码如下:

$title = "http://siyizhu.com测试模板";
$file = "TwoMax Inter test templet,
author:[email=Matrix@Two_Max]Matrix@Two_Max[/email]";
$fp = fopen ("temp.html","r");
$content = fread($fp,filesize ("temp.html"));
$content = str_replace("{file}",$file,$content);
$content = str_replace("{title}",$title,$content);
$filename = "test/test.html";
$handle = fopen ($filename,"w"); //打开文件指针,创建文件
/*  检查文件是否被创建且可写 */
if (!is_writable ($filename))
{
die ("文件:".$filename."不可写,请检查其属性后重试!");
}
if (!fwrite ($handle,$content))
{ //将信息写入文件
die ("生成文件".$filename."失败!");
}
fclose ($handle); //关闭指针
die ("创建文件".$filename."成功!");
?>

这一步比较简单。只是单纯的变量替换即可。如果要生成静态的列表页面的话,原理也是一样,用程序来生成文章列表,把它当成一个大的变量,替换模版中的变量,列表的翻页页是如此。当然,如果有信息更新的话,列表翻页也是要重新生成的。
PHP代码
复制代码 代码如下:

$title = "http://";
$file = "TwoMax Inter test templet,
author:[email=Matrix@Two_Max]Matrix@Two_Max[/email]";
$fp = fopen ("temp.html","r");
$content = fread ($fp,filesize ("temp.html"));
$content = str_replace ("{file}",$file,$content);
$content = str_replace ("{title}",$title,$content);
// 生成列表开始
$list = '';
$sql = "select id,title,filename from article";
$query = mysql_query ($sql);
while($result = mysql_fetch_array ($query))
{
$list .= ''.$result['title'].'
';
}
$content .= str_replace("{articletable}",$list,$content);//生成列表结束
// echo $content;
$filename = "test/test.html";
$handle = fopen ($filename,"w");
//打开文件指针,创建文件
/* 检查文件是否被创建且可写 */
if(!is_writable ($filename))
{
die ("文件:".$filename."不可写,请检查其属性后重试!");
}
if(!fwrite($handle,$content))
{ //将信息写入文件
die ("生成文件".$filename."失败!");
}
fclose($handle); //关闭指针
die ("创建文件".$filename."成功!");
?>

关于翻页:
如我们指定分页时,每页20篇。某子频道列表内文章经数据库查询为45条,则,首先我们通过查询得到如下参数:1,总页数;2,每页篇数。第二步,for ($i = 0; $i 例:
PHP代码
复制代码 代码如下:

$fp = fopen ("temp.html","r");
$content = fread ($fp,filesize ("temp.html"));
$onepage = '20';
$sql = "select id from article where channel='$channelid'";
$query = mysql_query ($sql);
$num = mysql_num_rows ($query);
$allpages = ceil ($num / $onepage);
for ($i = 0;$i{
if ($i == 0)
{
$indexpath = "index.html";
}
else
{
$indexpath = "index_".$i."html";
}
$start = $i * $onepage;
$list = '';
$sql_for_page = "select name,filename,title from article where channel='$channelid' limit $start,$onepage";
$query_for_page = mysql_query ($sql_for_page);
while ($result = $query_for_page)
{
$list .= ''.$title.'
';
}
$content = str_replace("{articletable}",$list,$content);
if (is_file ($indexpath))
{
@unlink ($indexpath); //若文件已存在,则删除
}
$handle = fopen ($indexpath,"w"); //打开文件指针,创建文件
/*检查文件是否被创建且可写 */
if (!is_writable ($indexpath))
{
echo "文件:".$indexpath."不可写,请检查其属性后重试!"; //修改为echo
}
if (!fwrite ($handle,$content))
{//将信息写入文件
echo "生成文件".$indexpath."失败!"; //修改为echo
}
fclose ($handle); //关闭指针
}
fclose ($fp);
die ("生成分页文件完成,如生成不完全,请检查文件权限系统后重新生成!");
?>

third:smarty模版生成静态页面
smarty自己有一个fetch函数,其功用有点类似于fread()可以用来生成静态的页面.
这个例子大家想必看起来眼熟,对,smarty手册中关于fetch函数的例子,比竟官方的例子总是很经典的嘛!
PHP代码
复制代码 代码如下:

include("Smarty.class.php");
$smarty = new Smarty;
$smarty->caching = true;
// only do db calls if cache doesn't exist
if(!$smarty->is_cached("index.tpl"))
{// dummy up some data
$address = "245 N 50th";
$db_data = array("City" => "Lincoln", "State" => "Nebraska", "Zip" => "68502");
$smarty->assign("Name","Fred");
$smarty->assign("Address",$address);
$smarty->assign($db_data);
}// capture the output
$output = $smarty->fetch("index.tpl");
//这个地方算是关键// do something with $output here
echo $output; //hoho 看到output的结果了吧 然后呢?fwrite一下,我们就得到我们所要的结果了。
$fp = fopen("archives/2005/05/19/0001.html", "w");
fwrite($fp, $content);
fclose($fp);
?>

PHP代码
复制代码 代码如下:

ob_start();
echo "Hello World!";
$content = ob_get_contents();//取得php页面输出的全部内容
$fp = fopen("archives/2005/05/19/0001.html", "w");
fwrite($fp, $content);
fclose($fp);
?>
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles