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

yipeiwu_com6年前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 解析xml 的四种方法详细介绍

php 解析xml 的四种方法 XML处理是开发过程中经常遇到的,PHP对其也有很丰富的支持,本文只是对其中某几种解析技术做简要说明,包括:Xml parser, SimpleXML,...

使用Curl进行抓取远程内容时url中文编码问题示例探讨

PHP中对于URL进行编码,可以使用 urlencode() 或者 rawurlencode(),二者的区别是前者把空格编码为 '+',而后者把空格编码为 '%20',不过应该注意的是,...

php类自动装载、链式操作、魔术方法实现代码

1、自动装载实例 目录下有3个文件:index.php load.php tests文件夹 tests文件夹里有 test1.php <?php namespace T...

php 解决扫描二维码下载跳转问题

php 解决扫描二维码下载跳转问题 首先我们指定一个url,比如 http://it.lovepet.vip 用这个地址生成二维码,二维码的生成方式有很多种,到网上搜搜就知道。 我们可...

PHP实现的单向散列加密操作示例

本文实例讲述了PHP实现的单向散列加密操作。分享给大家供大家参考,具体如下: 1.加密文件 <?php //sha1_en.php header("content-ty...