php实现文件编码批量转换


Posted in PHP onMarch 10, 2014

有些问题,不能重复转,比如gbk转到utf8,然后有在转成utf8,这样会乱码,我本来试图在转换之前去检测编码的,貌似失败了。我特意试了一个文件,我检测它是是否是gbk或者是utf-8,都返回true。这就不懂了。

<?php
/**
 * 转换文件编码
 * 依赖的扩展filesystem 和 mbstring
 * @example
 * <pre>
 * include_once 'ConvertEncode.php';
 * $convert = new ConvertEncode();
 * try{
 *   $convert->setPath('my', true, true);//目录
 *    //$convert->setPath('my.php');//单文件
 *   $convert->setEncode('GBK', 'UTF-8');
 *   $convert->convert();
 * }catch(ConvertException $e) {
 *   echo $e->getMessage();
 * }
 * </pre>
 */
class ConvertEncode { /**
  * 要转换成的编码
  * @var string
  */
 private $_to_encoding;
 /**
  * 转换前的编码
  * @var string
  */
 private $_from_encoding;
 /**
  * 要转换的的目录或者单文件
  * @var string
  */
 private $_path;
 /**
  * 是否是一个目录,当给出的是目录是才设置
  * @var boolean
  */
 private $_directory;
 /**
  * 是否递归遍历,仅对目录有效
  * @var boolean
  */
 private $_recursion;
 /**
  * 保存所有待转换的文件,仅当转换目录里面的文件时才用
  * @var array
  */
 private $_files = array();
 /**
  * 构造函数
  */
 public function __construct() {
  if( ! function_exists('mb_convert_encoding') ) {
   throw new ConvertException('mbstring extension be required');
  }
 }
 /**
  * 设置需要转换的目录或者单文件
  * @param string $path 目录或者文件
  * @param boolean 是否是目录
  * @param boolean 是否递归目录
  * @return boolean
  */
 public function setPath($path, $is_dir = false, $rec = false) {
  $this->_path = $path;
  $this->_directory = $is_dir;
  $this->_recursion = $rec;
  return true;
 }
 /**
  * 设置转换前的编码和要转换到的编码
  * @param string $encode 转换前的编码
  * @param string $encode 转换到的编码
  * @return boolean
  */
 public function setEncode($encode_from, $encode_to) {
  $this->_from_encoding = $encode_from;
  $this->_to_encoding   = $encode_to;
  return true;
 }
 /**
  * 转换编码,根据是否是目录的设置分别转换
  * @return boolean
  */
 public function convert() {
  if($this->_directory ) {
   return $this->_convertDirectory();
  }
  return $this->_convertFile();
 }
 /**
  * 转换文件
  * @throws ConvertException
  * @return boolean
  */
 private function _convertFile() {
  if( ! file_exists($this->_path) ) {
   $message = $this->_path . ' does not exist.';
   throw new ConvertException($message);
  }
  if( ! is_file($this->_path) ) {
   $message = $this->_path . ' is not a file.';
   throw new ConvertException($message);
  }
  if( ! $this->_isWR() ) {
   $message = $this->_path . ' must can be read and write.';
   throw new ConvertException($message);
  }
  $file_real_path    = realpath($this->_path);
  $file_content_from = file_get_contents( $file_real_path );
  if( mb_check_encoding($file_content_from, $this->_from_encoding) ) {
   $file_content_to   = mb_convert_encoding( $file_content_from, $this->_to_encoding, $this->_from_encoding );
   file_put_contents( $file_real_path, $file_content_to );
  }
  return true;
 }
 /**
  * 转换目录
  * @throws ConvertException
  * @return boolean
  */
 private function _convertDirectory() {
  if( ! file_exists($this->_path) ) {
   $message = $this->_path . ' does not exist.';
   throw new ConvertException($message);
  }
  if( ! is_dir($this->_path) ) {
   $message = $this->_path . ' is not a directory.';
   throw new ConvertException($message);
  }
  if( ! $this->_isWR() ) {
   $message = $this->_path . ' must can be read and write.';
   throw new ConvertException($message);
  }
  $this->_scanDirFiles();
  if( empty($this->_files) ) {
   $message = $this->_path . ' is a empty directory.';
   throw new ConvertException($message);
  }
  foreach( $this->_files as $value ) {
   $file_content_from = file_get_contents( $value );
   if( mb_check_encoding($file_content_from, $this->_from_encoding) ) {
    $file_content_to   = mb_convert_encoding( $file_content_from, $this->_to_encoding, $this->_from_encoding );
    file_put_contents( $value, $file_content_to );
   }
  }
  return true;
 }
 /**
  * 判断文件或者目录是否可读写
  * @return boolean 可读写时返回true,否则返回false
  */
 private function _isWR() {
  if( is_readable($this->_path) && is_writable($this->_path) ) {
   return true;
  }
  return false;
 }
 /**
  * 遍历目录,找出所有文件,加上绝对路径
  * @return boolean
  */
 private function _scanDirFiles($dir = '') {
  $base_path = empty( $dir ) ? realpath($this->_path) . DIRECTORY_SEPARATOR : realpath($dir) . DIRECTORY_SEPARATOR;
  $files_tmp = empty( $dir ) ? scandir($this->_path) : scandir($dir);
  foreach( $files_tmp as $value ) {
   if( $value == '.' || $value == '..' || ( strpos($value, '.') === 0 ) ) {
    continue;
   }
   $value = $base_path . $value;
   if( is_dir($value) ) {
    if( $this->_recursion ) {
     $this->_scanDirFiles($value);
    }
   }
   elseif( is_file($value) ) {
    $this->_files[] = $value;
   }
  }
  return true;
 }
}

/**
 * 转换异常
 *
 */
class ConvertException extends Exception {
}
PHP 相关文章推荐
php 文件上传后缀名与文件类型对照表(几乎涵盖所有文件)
May 16 PHP
PHP的博客ping服务代码
Feb 04 PHP
浅析php原型模式
Nov 25 PHP
php中PDO方式实现数据库的增删改查
May 17 PHP
php实现简单的MVC框架实例
Sep 23 PHP
谈谈PHP中substr和substring的正确用法及相关参数的介绍
Dec 16 PHP
分享50个提高PHP执行效率的技巧
Dec 26 PHP
PHP实现的浏览器检查类
Apr 11 PHP
简单解析PHP程序的运行流程
Jun 23 PHP
PHP下载远程图片的几种方法总结
Apr 07 PHP
PHP读取word文档的方法分析【基于COM组件】
Aug 01 PHP
laravel框架中表单请求类型和CSRF防护实例分析
Nov 23 PHP
php导出word文档与excel电子表格的简单示例代码
Mar 08 #PHP
php 创建以UNIX时间戳命名的文件夹(示例代码)
Mar 08 #PHP
PHP_Cooikes不同页面无法传递的解决方法
Mar 07 #PHP
php function用法如何递归及return和echo区别
Mar 07 #PHP
详解PHP中strlen和mb_strlen函数的区别
Mar 07 #PHP
解决Codeigniter不能上传rar和zip压缩包问题
Mar 07 #PHP
php 生成自动创建文件夹并上传文件的示例代码
Mar 07 #PHP
You might like
使用eAccelerator加密PHP程序
2008/10/03 PHP
PHP5中使用DOM控制XML实现代码
2010/05/07 PHP
PHP函数http_build_query使用详解
2014/08/20 PHP
php生成图片验证码-附五种验证码
2015/08/19 PHP
PHP实现上传多文件示例代码
2017/02/20 PHP
laravel5.6实现数值转换
2019/10/23 PHP
基于JQuery实现异步刷新的代码(转载)
2011/03/29 Javascript
将字符串转换成gb2312或者utf-8编码的参数(js版)
2013/04/10 Javascript
在JavaScript中访问字符串的子串
2015/07/07 Javascript
JS实现简易留言板增删功能
2020/02/08 Javascript
小程序websocket心跳库(websocket-heartbeat-miniprogram)
2020/02/23 Javascript
vue.js实现h5机器人聊天(测试版)
2020/07/16 Javascript
[56:21]LGD vs IG 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
Python模块学习 re 正则表达式
2011/05/19 Python
详解Python中expandtabs()方法的使用
2015/05/18 Python
python实现可以断点续传和并发的ftp程序
2016/09/13 Python
用pickle存储Python的原生对象方法
2017/04/28 Python
python2.7读取文件夹下所有文件名称及内容的方法
2018/02/24 Python
Centos7 Python3下安装scrapy的详细步骤
2018/03/15 Python
PyQt5每天必学之组合框
2018/04/20 Python
用python处理图片之打开\显示\保存图像的方法
2018/05/04 Python
在python中pandas的series合并方法
2018/11/12 Python
对pandas通过索引提取dataframe的行方法详解
2019/02/01 Python
python实现自动化报表功能(Oracle/plsql/Excel/多线程)
2019/12/02 Python
django框架cookie和session用法实例详解
2019/12/10 Python
关于pytorch处理类别不平衡的问题
2019/12/31 Python
pytorch SENet实现案例
2020/06/24 Python
一款纯css3实现的漂亮的404页面的实例教程
2014/11/27 HTML / CSS
CSS3实现滚动条动画效果代码分享
2016/08/03 HTML / CSS
Sunglass Hut巴西网上商店:男女太阳镜
2020/10/04 全球购物
文明家庭先进事迹材料
2014/05/14 职场文书
超市客服工作职责
2014/06/11 职场文书
中国梦团日活动总结
2014/07/07 职场文书
工程催款通知书
2015/04/17 职场文书
不会写演讲稿,快来看看这篇文章!
2019/08/06 职场文书
SQL Server中使用判断语句(IF ELSE/CASE WHEN )案例
2021/07/07 SQL Server