編碼轉換
這段代碼是ThinkPHP框架中的,感覺很常用,所以單獨拎出來,大家共同學習一下。
function auto_charset($fContents,$from='',$to='')
{
if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){
//如果編碼相同或者非字符串標量則不轉換
return $fContents;
}
$from = strtoupper($from)=='UTF8'? 'utf-8':$from;
$to = strtoupper($to)=='UTF8'? 'utf-8':$to;
if(is_string($fContents) ) {
if(function_exists('mb_convert_encoding')){
return mb_convert_encoding ($fContents, $to, $from);
}elseif(function_exists('iconv')){
return iconv($from,$to,$fContents);
}else{
exit('轉換失敗');
return $fContents;
}
}
elseif(is_array($fContents)){
foreach ( $fContents as $key => $val ) {
$_key = auto_charset($key,$from,$to);
$fContents[$_key] = auto_charset($val,$from,$to);
if($key != $_key ) {
unset($fContents[$key]);
}
}
return $fContents;
}
elseif(is_object($fContents)) {
$vars = get_object_vars($fContents);
foreach($vars as $key=>$val) {
$fContents->$key = auto_charset($val,$from,$to);
}
return $fContents;
}
else{
return $fContents;
}
}