今天在使用php时掉进了一个坑里,折腾了好久。 在使用json_encode时,如果数组中存在中文,该中文输出为null。 示例代码:
<?<span php </span><span $brand</span> = <span array</span>('id'=>'123456','name'=>'联想'<span ); </span><span var_dump</span>(json_encode(<span $brand</span><span )); </span>?>
输出结果:
<span string</span>(27) "{"id":"123456","name":null}"
<?<span php </span><span function</span> gbk2utf8(<span $data</span><span ){ </span><span if</span>(<span is_array</span>(<span $data</span><span )){ </span><span return</span> <span array_map</span>('gbk2utf8', <span $data</span><span ); } </span><span return</span> <span iconv</span>('gbk','utf-8',<span $data</span><span ); } </span>?>
<?<span php </span><span $brand</span> = <span array</span>('id'=>'123456','name'=>'联想'<span ); </span><span var_dump</span>(json_encode(gbk2utf8(<span $brand</span><span ))); </span>?>
在json_encode之前做一下gbk2utf8转码,此时输出正确结果。
<span string</span>(37) "{"id":"123456","name":"\u8054\u60f3"}"
\u8054\u60f3 为“联想”的unicode码,浏览器会自动转换成文字。