php的编码处理

目前遇到过两种情况:

1、php通过echo命令输出中文时,由于不同服务器的环境编码,有可能不一致,因此需要先声明:

header("Content-Type:text/html;charset=utf-8");

2、请求某些接口时,接口返回数据中有可能包含中文字符,为了能很好的解析出来,需要做适当的转码:

$data = 请求接口得到的数据(json字符串格式);

//判断一下编码类型
$data_encode = mb_detect_encoding($data, 'utf-8,gbk,gb2312');

//非utf-8,就转换之
if( 'utf-8' != strtolower($data_encode)) {
    $data = mb_convert_encoding($data, 'utf-8', $data_encode);
}

//最后将数据转换成数组,如果编码不正确,就会导致return null
return json_decode($data, true);

 

posted @ 2013-01-06 18:05  郎涛  阅读(114)  评论(0)    收藏  举报