php转换文件编码的方法:
代码
<?phpdefine('this_file', __file__); // 此文件路径,请勿修改,将跳过此文件define('this_path', dirname(this_file)); // 当前路径,可修改define('cover', 'new'); // 是否直接覆盖本文件(改为 true 不加单引号,危险),建议写入其他地址(相对于当前路径)define('ds', directory_separator); // linux改为'/',windows为'\\'define('iconv', 'utf-8'); // 最终转换编码格式function eachfile($path, $files = []){ if (cover !== true && $path == this_path . ds . cover) { return $files; } if (preg_match("/[\x7f-\xff]/", $path)) { $path = iconv('utf-8', 'gbk', $path); } if (is_file($path)) { $files[] = $path; return $files; } $list = scandir($path); foreach ($list as $k => $v) { if ($v !== '.' && $v !== '..') { $p = $path . ds . $v; // 路径转码gbk if (preg_match("/[\x7f-\xff]/", $p)) { $p = iconv('utf-8', 'gbk', $p); } if (is_dir($p)) { $files = eachfile($p, $files); } else { $files[] = $p; } } } return $files;}$files = eachfile(this_path);foreach ($files as $k => $v) { $ext = pathinfo($v, pathinfo_extension); if (in_array($ext, ['txt', 'php', 'css', 'js', 'htm', 'html'])) { if ($v == this_file) continue; // 获取内容并转码 $contents_before = file_get_contents($v); $oldiconv = mb_detect_encoding($contents_before, array('ascii', 'gb2312', 'gbk', 'utf-8', 'big5')); $contents_after = iconv($oldiconv, iconv, $contents_before); if (cover !== true) { // 判断新文件夹是否存在 $newpath = str_replace(this_path, this_path . ds . cover, $v); if (!file_exists(dirname($newpath))) { mkdir(dirname($newpath), 0755, true); } // 覆盖写入文件(不存在自动创建) file_put_contents($newpath, $contents_after); } else { file_put_contents($v, $contents_after); } // 输出 echo "{$v} 已转换<hr>"; } else { $newpath = str_replace(this_path, this_path . ds . cover, $v); if (cover !== true && !file_exists($newpath)) { if (!file_exists(dirname($newpath))) { mkdir(dirname($newpath), 0755, true); } copy($v, $newpath); echo "{$v} 复制文件到新路径 {$newpath}<hr>"; } }}
功能
自定义文件夹
跳过本文件(同一文件夹)及新文件夹(多次转码)
文件格式限制
转换文件编码到新文件夹(推荐)或本文件
复制无需转码文件到新文件夹
注意
暂未在linux上测试
只能转码文本文件
相关免费学习推荐:php编程(视频)
以上就是php如何转换文件编码的详细内容。