php批量生成静态文件

 1 <?php 
 2 require_once './config.inc.php';
 3 $m = new Model();
 4 $ids = $m->getAll("SELECT id FROM article ORDER BY id ASC");
 5 foreach ($ids as $rowIdArr) {
 6     $idStr .= $rowIdArr['id'].',';
 7 }
 8 $idStr = rtrim($idStr, ','); // 所有文章的 ID 号集合
 9 $idArr = explode(',', $idStr); // 分割成数组
10 // 下面的程序循环生成静态页面
11 foreach ($idArr as $articleId) {
12     $re = $m->getAll("SELECT id,title,date,author,source,content FROM article WHERE id =". $articleId); // $re 为每篇文章的内容,注意:其类型为:PDOStatement
13     $article = array(); // $article 为一个数组,保存每篇文章的title、date、author、content、source
14     foreach ($re as $r) {
15         $article = array(
16                     'title'=>$r['title'],
17                     'date'=>$r['date'],
18                     'author'=>$r['author'],
19                     'source'=>$r['source'],
20                     'content'=>$r['content']
21                 );
22     }
23     $articlePath = ROOT_PATH. '/article'; // $articlePath 为静态页面放置的目录
24     if (!is_dir($articlePath)) mkdir($articlePath, 0777); // 检查目录是否存在,不存在则创建
25     $fileName = ROOT_PATH . '/article/' . $articleId . '.html'; // $fileName 生成的静态文件名,格式:文章ID.html(主键ID不可能冲突)
26     $articleTemPath = ROOT_PATH . '/templates/article.html'; // $articleTemPath 文章模板路径
27     $articleContent = file_get_contents($articleTemPath); // 获取模板里面的内容
28     // 对模板里面设置的变量进行替换。即比如:把模板里面的 <{title}> 替换成数据库里读取的 title,替换完毕赋值给变量 $articleContent
29     $articleContent = getArticle(array_keys($article), $articleContent, $article);
30     $resource = fopen($fileName, 'w');
31     file_put_contents($fileName, $articleContent); // 写入 HTML 文件
32 }
33 
34 /**
35  * getArticle($arr, $content, $article) 对模板进行替换操作
36  * @param array $arr 替换变量数组
37  * @param string $content 模板内容
38  * @param array $article 每篇文章内容数组,格式:array('title'=>xx, 'date'=>xx, 'author'=>xx, 'source'=>xx, 'content'=>xx);
39  */
40 function getArticle($arr, $content, $article) {
41     // 循环替换
42     foreach ($arr as $item) {
43         $content = str_replace('<{'. $item .'}>', $article[$item], $content);
44     }
45     return $content;
46 }
47 ?>

 

转载于:https://www.cnblogs.com/lh460795/archive/2013/04/06/3003067.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值