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

yipeiwu_com5年前PHP代码库
首先建立一个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);
?>

相关文章

php 常用类整理

图表库 下面的类库可以让你很简单就能创建复杂的图表和图片。当然,它们需要GD库的支持。 pChart - 一个可以创建统计图的库。 Libchart - 这也是一个简单的统计图库。 Jp...

PHP中替换键名的简易方法示例详解

YII框架中封装好了的数据库操作函数,默认输出的时候,将数据库字段名作为数组的键名进行输出,但是有些时候带有键名的数据不能够满足未知情况下的操作,譬如:数据库数据导出为EXCEL等比较非...

php使用explode()函数将字符串拆分成数组的方法

本文实例讲述了php使用explode()函数将字符串拆分成数组的方法。分享给大家供大家参考。具体分析如下: explode()函数:字符串拆分成数组 示例代码如下: <...

PHP JSON出错:Cannot use object of type stdClass as array解决方法

php再调用json_decode从字符串对象生成json对象时,如果使用[]操作符取数据,会得到下面的错误: 复制代码 代码如下: Cannot use object of type...

php自动加载的两种实现方法

php自动载方法有两种. 第一种方案用__autoload,这个函数较简单,也较弱. 但有一问题没有解决, 就是在include前判断文件是否存在的问题. 复制代码 代码如下: set_...