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钩子与简单分发方式实例分析

本文实例讲述了PHP钩子与简单分发方式。分享给大家供大家参考,具体如下: //简单的钩子实现例子 class tool{ public static function main(...

php curl 模拟登录并获取数据实例详解

PHP的curl()在抓取网页的效率方面是比较高的,而且支持多线程,而file_get_contents()效率就要稍低些,当然,使用curl时需要开启下curl扩展。 代码实战 先来看...

php判断目录存在的简单方法

PHP判断文件或目录是否存在 file_exists:判断文件是否存在 $file = "check.txt"; if(file_exists($file)) { echo...

php开发时容易忘记的一些技术细节

在做开发的时候,有可能会忘记掉一些技术细节。这些细节有可能会造成很严重的后果,比如网站被注入、网站崩溃等等。现在我们总结一下,有可能会遇到的一些 PHP 中的一些 “陷阱”。 陷阱一:e...

php实现的通用图片处理类

本文实例讲述了php实现的通用图片处理类。分享给大家供大家参考。具体如下: 该图片处理函数功能:缩放、剪切、相框、水印、锐化、旋转、翻转、透明度、反色,处理并保存历史记录的思路:当有图片...