php怎么转为txt格式文件,用php实现把txt文件转为htm的代码

这个PHP脚本用于将指定目录下的所有.txt文本文件转换为包含CSS样式的.htm文件,转换后的文件保存在同一个目录下的htm子目录中。它首先检查输入目录是否存在,然后创建输出目录,接着遍历目录中的所有文件,将.txt文件转换为.htm文件,并在其中添加样式。如果文件已存在,脚本会跳过该文件。
摘要由CSDN通过智能技术生成

/*

批量把某目录下的所有.txt文件转化为对应的htm文件,该htm文件包含有方便阅读的css样式

生成的htm文件放在同一目录下htm目录下

参数1:要转化的目录的路径

执行 php txt2htm.php "C:\\txt\\"

php txt2htm.php "/tmp/txt/"

php txt2htm.php .

*/

$basedir=$argv[1];

if(!$basedir||!is_dir($basedir))

{

die("please input dir.\n");

}

//改变工作目录

chdir($basedir);

$d = dir(".");

//创建输出目录

$outputdir="./htm/";

if(!is_dir($outputdir)){

mkdir($outputdir, 0700);

}

//判断是否创建成功

if(!is_dir($outputdir))

{

die("cannot mkdir.\n");

}

while (false !== ($entry = $d->read()))

{

//判断是不是文件

if(is_file($entry))

{

$filename=strtolower($entry);

//判断是不是txt文件

if(stristr($filename,".txt"))

{

$wfile=$outputdir.basename($filename,".txt").".htm";

//若是文件已经存在,则跳过

if(file_exists($wfile))

{

echo "**********".$wfile." is exists ,skip this file**************\n";

continue;

}

if($str=file_get_contents($entry))

{

//写入样式,和换行

$str="

".str_replace("\n","\n
",$str);

if($fp=fopen($wfile,"w"))

{

if (fwrite($fp,$str) === FALSE) {

//写入失败

echo $wfile." cover fail! fwrite fail\n";

}else{

echo $wfile." cover success!\n";

}

fclose($fp);

}else{

//创建文件失败

echo $wfile." cover fail! fopen fail\n";

}

}else{

//读取失败

echo $wfile." cover fail! file_get_contents fail\n";

}

}

}

}

$d->close();

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值