在网上看到json的文章,打算测试一下,结果,出现错误,先附上代码:
"贾朝藤",'age'=>19,'sex'=>"男",'add'=>"中国石家庄"); echo json_encode($arr); echo "
"; $name = iconv("GBK","UTF-8","贾朝藤"); $sex = iconv("GBK","UTF-8","男"); $add = iconv("GBK","UTF-8","中国石家庄"); $arr = array ('name'=>"$name",'age'=>19,'sex'=>"$sex",'add'=>"$add"); echo $str=json_encode($arr); ?>
错误信息如下:
{"name":"/u8d3e/u671d/u85e4","age":19,"sex":"/u7537","add":"/u4e2d/u56fd/u77f3/u5bb6/u5e84"} Notice: iconv() [function.iconv]: Detected an illegal character in input string in D:/wamp/www/ajax/js_php.php on line 6 Notice: iconv() [function.iconv]: Detected an illegal character in input string in D:/wamp/www/ajax/js_php.php on line 7 Notice: iconv() [function.iconv]: Detected an illegal character in input string in D:/wamp/www/ajax/js_php.php on line 8 {"name":"/u7490/u70ac","age":19,"sex":"","add":"/u6d93"}
之后百度,谷歌了一番,得到两个方法:
1.把gb2312换为gbk ,同样出错,错误信息如下
"name":"/u8d3e/u671d/u85e4","age":19,"sex":"/u7537","add":"/u4e2d/u56fd/u77f3/u5bb6/u5e84"} Notice: iconv() [function.iconv]: Detected an incomplete multibyte character in input string in D:/wamp/www/ajax/js_php.php on line 6 Notice: iconv() [function.iconv]: Detected an incomplete multibyte character in input string in D:/wamp/www/ajax/js_php.php on line 7 Notice: iconv() [function.iconv]: Detected an illegal character in input string in D:/wamp/www/ajax/js_php.php on line 8 {"name":"/u7490/u70ac/u6e5e/u9498","age":19,"sex":"/u9422","add":"/u6d93"}
2.在UTF-8后加//IGNORE ,加上后提示如下:
{"name":"/u8d3e/u671d/u85e4","age":19,"sex":"/u7537","add":"/u4e2d/u56fd/u77f3/u5bb6/u5e84"} Notice: iconv() [function.iconv]: Detected an incomplete multibyte character in input string in D:/wamp/www/ajax/js_php.php on line 6 Notice: iconv() [function.iconv]: Detected an incomplete multibyte character in input string in D:/wamp/www/ajax/js_php.php on line 7 {"name":"/u7490/u70ac/u6e5e/u9498","age":19,"sex":"/u9422","add":"/u6d93/u9365/u754c/u7176/u7039/u8dfa/u7c1e"}
不解,之后在论坛提问,得到问题所在:
我的php文件本身是utf-8编码的,把它转为ansi这个问题就不存在
修改之后,确实,显示正常了!
论坛还有个朋友,给我推荐了个函数
string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding ] )
需要编译时加一个参数--enable-mbstring
对了,附上json转换php数组跟js数组的文章地址也加上,个人感觉文章不错
http://www.phpchina.com/index.php?action-viewthread-tid-15585