当前位置:首页 > PHP教程 > php文件操作 > 列表

php 遍历目录文件编码转换

发布:smiling 来源: PHP粉丝网  添加日期:2018-09-14 13:40:33 浏览: 评论:0 

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

  1. //php iconv.php  
  2.  
  3. //exec it on root dir 
  4.  
  5. $path = dirname(__FILE__); 
  6.  
  7. tree($path); 
  8.  
  9.   
  10.  
  11. function encodeFiles($fileName) 
  12.  
  13. { 
  14.  
  15. //    echo $fileName; 
  16.  
  17.     if (file_exists($fileName)) { 
  18.  
  19.         // Read in the contents 
  20.  
  21.         $res = file_get_contents($fileName); 
  22.  
  23.         $i = pathinfo($fileName); 
  24.  
  25.         if(!in_array($i['extension'],array('js','css','php','html','htm'))){ 
  26.  
  27.             return ; 
  28.  
  29.         } 
  30.  
  31.         // Just display on the screen the file being modified 
  32.  
  33.         echo  $fileName . "---form---"; 
  34.  
  35.         // Convert the contents 
  36.  
  37.         echo  $encode = mb_detect_encoding()($res, array("ASCII", "UTF-8", "GB2312", "GBK")); 
  38.  
  39.         echo "---to---UTF-8!\n"; 
  40.  
  41.         $res = iconv($encode, "UTF-8", $res); 
  42.  
  43.         // Write back out to the same file 
  44.  
  45.         file_put_contents($fileName, $res); 
  46.  
  47.     } // 
  48.  
  49. } 
  50.  
  51.   
  52.  
  53. function tree($directory) 
  54.  
  55. { 
  56.  
  57.     $mydir = dir($directory); 
  58.  
  59.     while ($file = $mydir->read()) { 
  60.  
  61.         if ((is_dir("$directory/$file")) AND ($file != ".") AND ($file != "..")) { 
  62.  
  63.             tree("$directory/$file"); 
  64.  
  65.         } else { 
  66.  
  67.             $file ="$directory/$file"; 
  68.  
  69.   
  70.  
  71. //            echo "<li>$file</li>\n"; 
  72.  
  73.             if(is_file($file)){ 
  74.  
  75.                 encodeFiles($file); 
  76.  
  77.             } 
  78.  
  79.         } 
  80.  
  81.     } 
  82.  
  83. } 

Tags: 编码 文件 目录

分享到: