现在的位置: 首页php实例>正文
php静态页面文件的目录  
发表于558 天前 php实例 评论关闭

对于php中的静态页面来说,数据库中记录的目录有时会生成静态的HTML文件。

访问者会浏览到。

php静态页面文件的目录通过读取数据库中的数据然后将记录逐条写入文件。

例如:

模板文件如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>目录</title>
</head>
<body>
<h1>目录</h1>
<hr />
<pre>%menu%</pre>

</body>
</html>

php代码如下:

<?php
//主程序开始
@mysql_connect("localhost","root","19860924")
or die("数据库服务器链接失败");
@mysql_select_db("mydb")
or die("数据库选择错误");
//执行sql语句
$query = mysql_query("select * from news")
or die("SQL语句执行失败");
$menu ='';
while ($record = mysql_fetch_array($query))
{
//读取记录中的title和filename
$title = $record['title'];
$filename = $record['filename'];
//生成链接的HTML代码
$link = "<a href='$filename'>$title</a>";
//将链接放到$menu中
$menu.=$link;
}
  $f_tem = fopen("template_3.htm","r"); //模板文件名称
  $f_new = fopen("menu.htm","w"); //生成的目录文件
  while (!feof($f_tem))
  {
   $row = fgets($f_tem);
   $row = str_replace("%menu%",$menu,$row);
   fwrite($f_new,$row);
  }
  fclose($f_new);
  fclose($f_tem);
  mysql_close();
?>

以下是对上面php例子的修正,添加了分页功能

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>目录</title>
</head>
<body>
<h1>目录</h1>
<hr />
<pre>%menu%</pre>
<a href="%prev%">PRE</a>|<a href="%next%">NEXT</a>
</body>
</html>
<?php
//主程序开始
@mysql_connect("localhost","root","19860924")
or die("数据库服务器链接失败");
@mysql_select_db("mydb")
or die("数据库选择错误");
//执行sql语句
$query = mysql_query("select * from news")
or die("SQL语句执行失败");
$pagesize = 5;
$i = 0;
$p = 0;
$menu='';
$sum = mysql_num_rows($query);
while ($record = mysql_fetch_array($query))
{
//读取记录中的title和filename
$title = $record['title'];
$filename = $record['filename'];
//生成链接的HTML代码
$link = "<a href='$filename'>$title</a>";
//将链接放到$menu中
$menu.=$link;
//计数
$i++;
//当计数器$i能整除$pagesize时或所有的记录都被取出时输出文件
if($i % $pagesize == 0 or $i == $sum)
{
$p++;
  $f_tem = fopen("template_4.htm","r");
  $f_new = fopen("menu$p.htm","w");
  if ($p > 1)
  {
  //计算上一页页码
  $prev = $p - 1;
  }
  else
  {
  $prev = $p;
  }
  if($i<$sum)
  {
  //计算下一页页码
  $next = $p + 1;
  }
  else
  {
  $next = $p;
  }

  while (!feof($f_tem))
  {
   $row = fgets($f_tem);
   $row = str_replace("%menu%",$menu,$row);
   $row = str_replace("%prev%","menu$prev.htm",$row);
   $row = str_replace("%next%","menu$next.htm",$row);
   fwrite($f_new,$row);
  }
   fclose($f_new);
  fclose($f_tem);
  $menu='';
  }
}
   mysql_close();
?>

报歉!评论已关闭.

不想听你唠叨×