欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

用php实现把txt文件转为htm的代码

程序员文章站 2022-06-10 12:18:19
...
  1. /*

  2. 批量把某目录下的所有.txt文件转化为对应的htm文件,该htm文件包含有方便阅读的css样式
  3. 生成的htm文件放在同一目录下htm目录下
  4. 参数1:要转化的目录的路径
  5. 执行 php txt2htm.php "C:\\txt\\"
  6. php txt2htm.php "/tmp/txt/"
  7. php txt2htm.php .
  8. */
  9. $basedir=$argv[1];

  10. if(!$basedir||!is_dir($basedir))
  11. {
  12. die("please input dir.\n");
  13. }
  14. //改变工作目录
  15. chdir($basedir);

  16. $d = dir(".");

  17. //创建输出目录
  18. $outputdir="./htm/";

  19. if(!is_dir($outputdir)){
  20. mkdir($outputdir, 0700);
  21. }
  22. //判断是否创建成功
  23. if(!is_dir($outputdir))

  24. {
  25. die("cannot mkdir.\n");
  26. }
  27. while (false !== ($entry = $d->read()))
  28. {
  29. //判断是不是文件
  30. if(is_file($entry))

  31. {
  32. $filename=strtolower($entry);
  33. //判断是不是txt文件
  34. if(stristr($filename,".txt"))

  35. {
  36. $wfile=$outputdir.basename($filename,".txt").".htm";
  37. //若是文件已经存在,则跳过
  38. if(file_exists($wfile))

  39. {
  40. echo "**********".$wfile." is exists ,skip this file**************\n";
  41. continue;
  42. }
  43. if($str=file_get_contents($entry))
  44. {
  45. //写入样式,和换行
  46. $str="

    ".str_replace("\n","\n
    ",$str);
  47. if($fp=fopen($wfile,"w"))
  48. {
  49. if (fwrite($fp,$str) === FALSE) {
  50. //写入失败
  51. echo $wfile." cover fail! fwrite fail\n";

  52. }else{
  53. echo $wfile." cover success!\n";
  54. }
  55. fclose($fp);
  56. }else{
  57. //创建文件失败
  58. echo $wfile." cover fail! fopen fail\n";

  59. }
  60. }else{
  61. //读取失败
  62. echo $wfile." cover fail! file_get_contents fail\n";

  63. }
  64. }
  65. }
  66. }
  67. $d->close();
  68. ?>
复制代码

运行: 用php实现把txt文件转为htm的代码 效果: 用php实现把txt文件转为htm的代码