PHP conversion folder under all file encoding implementation code

  • 2020-06-07 04:05:50
  • OfStack

The encoding of all the files in the PHP conversion folder is suitable for publishing other versions of the website. For example, if you have a version of GBK and you want to have a version of UTF8 or if you only have the source code of GBK and you want to develop it twice but you don't want to change the encoding of IDE, you can use this program to batch convert it to UTF8:
The code is as follows:

<?php
/**
*  the 1 All the files in the folders are transcoded   Only turn 1 time   Otherwise, all the code will become chaotic 
* @param string $filename
*/
function iconv_file($filename,$input_encoding='gbk',$output_encoding='utf-8')
{
if(file_exists($filename))
{
if(is_dir($filename))
{
foreach (glob("$filename/*") as $key=>$value)
{
iconv_file($value);
}
}
else
{
$contents_before = file_get_contents($filename);
/*$encoding = mb_detect_encoding($contents_before,array('CP936','ASCII','GBK','GB2312','UTF-8'));
echo $encoding;
if($encoding=='UTF-8') mb_detect_encoding Function doesn't work 
{
return;
}*/
$contents_after = iconv($input_encoding,$output_encoding,$contents_before);
file_put_contents($filename, $contents_after);
}
}
else
{
echo ' Parameter error ';
return false;
}
}
iconv_file('./test');
?>


Related articles: