PHP 生成HTML文件
<!--
学完了后才知道,这就是文件操作方面的内容,并非新知识。
-->
大部分的文件函数之前已经接触了。这里只说几个重要的:
resource fopen ( string$filename , string$mode [, bool$use_include_path= false [, resource$context ]] ) //打开文件,有只读,只写,读写模式
int filesize ( string$filename ) // 获取文件的大小
int fwrite ( resource$handle , string$string [, int$length ] ) //写入文件
string fread ( resource$handle , int$length ) //读文件,可以读二进制文件
bool unlink ( string$filename [, resource$context ] ) //删除文件
更多更详细的内容:
http://php.net/
简单型:
<?php
$in="tt.txt";
$fp=fopen($in,"r");
$get=fread($fp,filesize($in));
$fp=fopen("out.htm","w");
fwrite($fp,$get);
fclose($fp);
?>
循环生成多个文件,用3个txt文件生成3个htm文件(相当于转化):
遇到的问题:
Warning: fopen(michaeljordan——杀手.htm): failed to open stream: Invalid argument
编码问题,生成文件确实成功了,但是文件名乱码,所以返回结果是不存在路径。改成英文即可.
<?php
$txtArray=array(array("t1.txt","fly.htm"),array("t2.txt","killer.htm"),
array("t3.txt","chamption.htm"));
foreach ($txtArray as $id=>$value){
$filename=$value[0];
$title=$value[1];
$fp=fopen($filename,"r");
$get=fread($fp,filesize($filename));
$fp=fopen($title,"w");
fwrite($fp,$get);
unlink($filename); //删除源文件
}
fclose($fp);
?>
实在想用中文命名htm文件,可以把php文件编码设成ASCII 码:
<?php
$txtArray=array(array("t1.txt","michael jordan——飞翔.htm"),array("t2.txt","michael jordan——杀手.htm"),
array("t3.txt","michael jordan——首冠.htm"));
foreach ($txtArray as $id=>$value){
$filename=$value[0];
$title=$value[1];
$fp=fopen($filename,"r");
$get=fread($fp,filesize($filename));
$fp=fopen($title,"w");
fwrite($fp,$get);
//unlink($filename); //删除源文件
}
fclose($fp);
?>
版权声明
本文仅代表作者观点,不代表博信信息网立场。