用json_decode()将数组/对象序列化为JSON字符串的时候基本上只支持 UTF-8/ASCII编码,而我们有的站采用了GBK/GB2312编码,这个时候,直接使用json_encode/json_decode的时候就可能会出问题了,代码如下:
<?php $json = '{"a":"中国人人"}'; var_dump(json_decode($json)); ?> //结果 //{"text":null,"status":1}
比如转含有中文的字符字变成空(null),但有时候我们又必须得用gb编码而又要用到json_decode()转换的时候呢?什么办呢?自己昨晚写了一个不用数据库的一个添加音乐的小后台,也就是用php添加音乐,然后生成xml菜单,不用数据库那也得用一个方式来保存数据了,保存成文本的数据再可以直接拿出来用的,我想是把数组json_decode()用它转成json格式,用的时候再拿出来用它json_encode转回数组就可以了(可能最近弄js被json影响了,好像把数组序列化还有更好的方法,比如用:serialize()和unserialize()),呵呵,转正题,既然json_decode()在gb编码上转不了中文,那么我们可以先把中文转成英文编码的形式,那可以使用这个urlencode()转一下编码,再做json_decode()转换,使用的时候,再用urldecode()转成中文就可以了,代码如下:
<?php /* 字符串GBK转码为UTF-8,数字转换为数字。 */ function ct2($s) { if (is_numeric($s)) { return intval($s); } else { return iconv("GBK", "UTF-8", $s); } } /* 批量处理gbk->utf-8 */ function icon_to_utf8($s) { if (is_array($s)) { foreach ($s as $key => $val) { $s[$key] = icon_to_utf8($val); } } else { $s = ct2($s); } return $s; } echo json_encode(icon_to_utf8("厦门")); ?>
本文地址:
转载随意,但请附上文章地址:-)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

SublimeText3 English version
Recommended: Win version, supports code prompts!
