Home > Backend Development > PHP Tutorial > Use php to implement the code to convert txt files to htm

Use php to implement the code to convert txt files to htm

WBOY
Release: 2016-07-25 08:51:30
Original
1073 people have browsed it
  1. /*

  2. Convert all .txt files in a certain directory into corresponding htm files in batches. The htm files contain easy-to-read css styles
  3. generated htm files Place it under the htm directory in the same directory
  4. Parameter 1: The path of the directory to be converted
  5. Execute 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. //Change working directory
  15. chdir($basedir);

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

  17. //Create output directory
  18. $outputdir="./htm/";

  19. if(!is_dir($outputdir)){
  20. mkdir($outputdir, 0700);
  21. }
  22. //Determine whether the creation is successful< ;/p>
  23. if(!is_dir($outputdir))

  24. {
  25. die("cannot mkdir.n");
  26. }
  27. while (false !== ($entry = $d->read ()))
  28. {
  29. //Judge whether it is a file
  30. if(is_file($entry))

  31. {
  32. $filename=strtolower($entry);
  33. //Judge whether it is a txt File
  34. if(stristr($filename,".txt"))

  35. {
  36. $wfile=$outputdir.basename($filename,".txt").".htm";
  37. //If the file already exists, skip
  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. //Writing style, and newline
  46. $str="

    ".str_replace("n", "n
    ",$str);
  47. if($fp=fopen($wfile,"w"))
  48. {
  49. if (fwrite($fp,$str) === FALSE) {
  50. //write Entry failed
  51. echo $wfile." cover fail! fwrite failn";

  52. }else{
  53. echo $wfile." cover success!n";
  54. }
  55. fclose($fp);
  56. }else{
  57. //Failed to create file
  58. echo $wfile." cover fail! fopen failn";

  59. }
  60. }else{
  61. //Failed to read
  62. < ;p> echo $wfile." cover fail! file_get_contents failn";
  63. }
  64. }
  65. }
  66. }
  67. $d->close();
  68. ?>
Copy code

Run: Use php to implement the code to convert txt files to htm Effect: Use php to implement the code to convert txt files to htm



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template