php Automatically Recognizes File Encoding and Converts to UTF 8

  • 2021-06-28 12:11:12
  • OfStack

PHP conversion file encoding is a relatively simple thing, but when passing Chinese parameters in development, sometimes do not know what encoding is, resulting in the phenomenon of random code.There is a very convenient solution to automatically recognize the encoding and convert it to UTF-8.The code is as follows:

function characet($data){
  if( !empty($data) ){    
    $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;   
    if( $fileType != 'UTF-8'){   
      $data = mb_convert_encoding($data ,'utf-8' , $fileType);   
    }   
  }   
  return $data;    
}


Related articles: