当前位置:首页 > PHP教程 > php高级应用 > 列表

PHP批量修改静态html文件编码的例子

发布:smiling 来源: PHP粉丝网  添加日期:2014-06-21 08:48:48 浏览: 评论:0 

一堆的文件编码都是ANSI的,本来想用linux shell批量修改文件编码,却不太熟悉,写了个PHP脚本批量修改html文件的编码,代码如下:

  1. <?php 
  2.  
  3. //1.遍历出所有html文件 
  4. $dir = './jquery/jquery/'; //文件目录、 
  5.  
  6. $move_to = './jquery/jquery_new/'; 
  7.  
  8. foreach(glob($dir . '*.htm*') as $html) 
  9. { 
  10.     //读取文件 
  11.     $fp = fopen($html, 'a+'); 
  12.     $html_string = fread($fp, filesize($html)); 
  13.      
  14.     //转码操作 
  15.     $html_string = str_replace('charset=gb2312', 'charset=UTF-8', $html_string); 
  16.      
  17.     $file_code = mb_detect_encoding()($html_string, array('UTF-8','GBK','LATIN1','BIG5')); 
  18.      
  19.     if($file_code = 'CP936') 
  20.     { 
  21.         $html_string = mb_convert_encoding($html_string ,'utf-8' , 'gbk'); 
  22.     } 
  23.      
  24.     //获取文件名 
  25.     $slice = explode('/', $html); 
  26.     $file_name = end($slice); 
  27.      
  28.     //移到新文件 
  29.     file_put_contents($move_to . $file_name, $html_string); 
  30.      
  31.     fclose($fp); 
  32. } 
  33.  
  34. echo 'ok, 执行完成'; 

其实主要用到mb_detect_encoding检测编码,使用mb_convert_encoding转换编码,这是mbstring扩展的函数,代码如下:

  1. <?php 
  2.  
  3. /** 
  4.  * 检测编码 
  5.  * string mb_detect_encoding ( string $str [, mixed $encoding_list = mb_detect_order() [, bool $strict = false ]] ) 
  6.  *  
  7.  * @param $str 要检测的字符串 
  8.  * @param $encoding_list 检测编码的顺序 
  9.  * @param $strict 是否严格检测编码 
  10.  */ 
  11.  
  12. $str = 'PHP点点通'; 
  13. echo $file_code = mb_detect_encoding($str, array('UTF-8','GBK','LATIN1','BIG5')); //UTF-8 
  14.  
  15. /** 
  16.  * 转换编码 
  17.  * string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding ] ) 
  18.  *  
  19.  * @param $str 要转换的字符串 
  20.  * @param $to_encoding 转换后的字符串 
  21.  * @param $from_encoding  
  22.  */ 
  23.  
  24. echo mb_convert_encoding($str, 'GBK', 'UTF-8'); 

Tags: PHP修改静态html文件

分享到: