使用php怎么批量生成html和txt文件

发布时间:2021-02-05 18:05:18 作者:Leah
来源:亿速云 阅读:213

这篇文章给大家介绍使用php怎么批量生成html和txt文件,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

首先建立一个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怎么批量生成html和txt文件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. PHP HTML生成word
  2. python中的requirements.txt文件的生成和使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php html txt

上一篇:PHP中printf和sprintf函数之间有什么区别

下一篇:PHP中获取对象属性的方法有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》