1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| $encoding_list = ['UTF-32LE', 'UTF-32BE', 'UTF-16LE', 'UTF-16BE', 'UTF-8', 'WINDOWS-1252'];
$directory = 'path/to/your/files/';
$extensions = ['txt', 'csv'];
$backup_dir = 'path/to/your/files/backup/';
$backup_ext = 'bak';
$file_list = glob($directory . '*.{' . implode(',', $extensions) . '}', GLOB_BRACE);
foreach($file_list as $file) {
$content = file_get_contents($file);
$encoding = mb_detect_encoding($content, $encoding_list, true);
if ( $encoding === 'UTF-8' )
continue;
$filename = substr(strrchr("/$file", '/'), 1);
if ( copy($file, $backup_dir . $filename . '.' . $backup_ext) === false ) {
echo 'impossible de copier ', $file, PHP_EOL;
continue;
}
file_put_contents($file, mb_convert_encoding($content, 'UTF-8', $encoding) );
} |
Partager