php轉(zhuǎn)換文件編碼的方法:使用函數(shù)【str_replace】轉(zhuǎn)換文件編碼到新文件夾,代碼為【$newPath = str_replace(THIS_PATH, THIS_PATH . DS . Cover, $v)】。
php轉(zhuǎn)換文件編碼的方法:
代碼
<?php define('THIS_FILE', __FILE__); // 此文件路徑,請(qǐng)勿修改,將跳過(guò)此文件 define('THIS_PATH', dirname(THIS_FILE)); // 當(dāng)前路徑,可修改 define('Cover', 'new'); // 是否直接覆蓋本文件(改為 true 不加單引號(hào),危險(xiǎn)),建議寫入其他地址(相對(duì)于當(dāng)前路徑) define('DS', DIRECTORY_SEPARATOR); // Linux改為'/',Windows為'\' define('ICONV', 'UTF-8'); // 最終轉(zhuǎn)換編碼格式 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; // 路徑轉(zhuǎn)碼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; // 獲取內(nèi)容并轉(zhuǎn)碼 $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); } // 覆蓋寫入文件(不存在自動(dòng)創(chuàng)建) file_put_contents($newPath, $contents_after); } else { file_put_contents($v, $contents_after); } // 輸出 echo "{$v} 已轉(zhuǎn)換<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} 復(fù)制文件到新路徑 {$newPath}<hr>"; } } }
功能
-
自定義文件夾
-
跳過(guò)本文件(同一文件夾)及新文件夾(多次轉(zhuǎn)碼)
-
文件格式限制
-
轉(zhuǎn)換文件編碼到新文件夾(推薦)或本文件
-
復(fù)制無(wú)需轉(zhuǎn)碼文件到新文件夾
注意
-
暫未在Linux上測(cè)試
-
只能轉(zhuǎn)碼文本文件
相關(guān)免費(fèi)學(xué)習(xí)推薦:php編程(視頻)