php 遍历目录文件编码转换

遍历当前目录及子目录,把所有的文件转换编码到UTF-8,代码如下:

  1. //php iconv.php
  2. //exec it on root dir
  3. $path = dirname(__FILE__);
  4. tree($path);
  5. function encodeFiles($fileName)
  6. {
  7. // echo $fileName;
  8. if (file_exists($fileName)) {
  9. // Read in the contents
  10. $res = file_get_contents($fileName);
  11. $i = pathinfo($fileName);
  12. if(!in_array($i['extension'],array('js','css','php','html','htm'))){
  13. return ;
  14. }
  15. // Just display on the screen the file being modified
  16. echo $fileName . "---form---";
  17. // Convert the contents
  18. echo $encode = mb_detect_encoding()($res, array("ASCII", "UTF-8", "GB2312", "GBK"));
  19. echo "---to---UTF-8!\n";
  20. $res = iconv($encode, "UTF-8", $res);
  21. // Write back out to the same file
  22. file_put_contents($fileName, $res);
  23. } //
  24. }
  25. function tree($directory)
  26. {
  27. $mydir = dir($directory);
  28. while ($file = $mydir->read()) {
  29. if ((is_dir("$directory/$file")) AND ($file != ".") AND ($file != "..")) {
  30. tree("$directory/$file");
  31. } else {
  32. $file ="$directory/$file";
  33. // echo "<li>$file</li>\n";
  34. if(is_file($file)){
  35. encodeFiles($file);
  36. }
  37. }
  38. }
  39. }