background image

PHP

代码 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>";

}

/* 

 

释放资源 */