json格式在开发中用的十分广泛。在php中json_encode函数可以直接将数组转成 json格式,十分方便。但是有可能你在使用json_encode函数时,无奈的发现中文被编码成null了。原来json只支持转义utf-8编码格式的中文。
所以如果你是数据是gbk格式或者gb2312格式 那么你就需要转码
header("Content-Type:text/html;charset=gb2312");
$name = trim($_GET['name']);
$data = $db->query("select name from engine where source=N'{$name}'");
// 调用转码函数
$datas = array_iconv($data);
print_r(json_encode($datas));die();/**
* [array_iconv 进行转码因为json函数支持gbk格式]
* @param [type] $arr [description]
* @param string $in_charset [description]
* @param string $out_charset [description]
* @return [type] [description]
*/
function array_iconv($arr, $in_charset = "gb2312", $out_charset = "utf-8") {
$ret = eval('return ' . iconv($in_charset, $out_charset, var_export($arr, true)) . ';');
return $ret;
}
此处我数据库查出来的数据是gb2312格式所以导致我json返回的中文一直为空,所以在返回的时候进行一下转码就好了
array_iconv这个函数就是作为转码使用
输出结果
这是未转码的
这是经过转码的
直接调用函数传值进去就行
标签:iconv,name,转码,charset,json,encode,格式,null
来源: https://www.cnblogs.com/lcxin/p/14458409.html