最近要混合使用一个比较老的database,然后无奈之下,发现各种数组需要转化字符集格式,修改了一次又一次,最后只能写两个相互转化的函数进行一下使用,后期有更好的方法可以告诉我,底下这俩,不管你一维数组还是多维,包括key值全给你转化喽,气的一匹
// php转化为gbk或者utf8的两个小方法
<?php
class upCon{
public function __construct(){
}
/**
* string set utf8
*/
public function toUtf8($arr)
{
if(is_array($arr)){
$res=array();
foreach($arr as $k=>$v){
$nowKey=$this->getUtf8($k);
$nowVal=$this->toUtf8($v);
$res[$nowKey]=$nowVal;
}
return $res;
}else{
$res=$this->getUtf8($arr);
return $res;
}
}
/**
* string set gbk
*/
public function toGbk($arr)
{
if(is_array($arr)){
$res=array();
foreach($arr as $k=>$v){
$nowKey=$this->getGbk($k);
$nowVal=$this->toGbk($v);
$res[$nowKey]=$nowVal;
}
return $res;
}else{
$res=$this->getGbk($arr);
return $res;
}
}
private function getUtf8($arr){
$encode = mb_detect_encoding($arr, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
if($encode=='UTF-8'){
return $arr;
}
$str_encode = mb_convert_encoding($arr, 'UTF-8', $encode);
//header("content-Type: text/html; charset=UTF-8");
// mb_convert_encoding($str, "UTF-8", "auto");
return $str_encode;
}
private function getGbk($arr){
$encode = mb_detect_encoding($arr, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
if($encode=='GBK'||$encode=='GB2312'){
return $arr;
}
$str_encode = mb_convert_encoding($arr, 'GBK', $encode);
//header("content-Type: text/html; charset=gb2312");
// mb_convert_encoding($str, "GBK", "auto");
return $str_encode;
}
}