网络编程 
首页 > 网络编程 > 浏览文章

php 批量生成html,txt文件的实现代码

(编辑:jimmy 日期: 2024/10/13 浏览:3 次 )
首先建立一个conn.php的文件用来链接数据库
复制代码 代码如下:
<?php
    $link = mysql_connect("mysql_host" , "mysql_user" , "mysql_password" )or die("Could not connect : " . mysql_error());
    mysql_query("set names utf8");
    mysql_select_db("my_database") or die("Could not select database");
?>

php 批量生成html
复制代码 代码如下:
<?php
    require_once(“conn.php”);
    $query = "SELECT id,title,introduce FROM my_table";
    $result = mysql_query($query) or die("Query failed : " . mysql_error());
    /* 生成 HTML 结果 */
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

        $id=$row['id'];
        $title=$row['title'];
        $introduce=$row['introduce'];
        $path="html/$id.html";
        $fp=fopen("template.html","r"); //只读打开模板
        $str=fread($fp,filesize("template.html"));//读取模板中内容
        $str=str_replace("{title}",$title,$str);
        $str=str_replace("{introduce}",$introduce,$str);//替换内容
        fclose($fp);
        $handle=fopen($path,"w"); //写入方式打开新闻路径
        fwrite($handle,strip_tags($introduce)); //把刚才替换的内容写进生成的HTML文件
        fclose($handle);
        //echo "<a href=html/$id.html>生成成功</a>"."<br>";
    }
    /* 释放资源 */
    mysql_free_result($result);
    mysql_close($link);
?>

template.html文件内容:
复制代码 代码如下:
<!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=utf-8" />
<title>{title}</title>
</head>
<body>
{introduce}
</body>
</html>

php 批量生成txt
复制代码 代码如下:
<?php
    require_once(“conn.php”);
    $query = "SELECT kid,title,introduce FROM pro_courses";
    $result = mysql_query($query) or die("Query failed : " . mysql_error());
    /* 生成 txt 结果 */
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

        $id=$row['id'];
        $title=$row['title'];
        $introduce=$row['introduce'];
        $path="html/$id.txt";
        $handle=fopen($path,"w"); //写入方式打开新闻路径
        fwrite($handle,strip_tags($introduce)); //把刚才替换的内容写进生成的txt文件
        fclose($handle);
    }
    /* 释放资源 */
    mysql_free_result($result);
    mysql_close($link);
?>
上一篇:安装apache2.2.22配置php5.4(具体操作步骤)
下一篇:php 去除html标记--strip_tags与htmlspecialchars的区别详解
一句话新闻
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。