微信自定义菜单说php json_encode不转义中文汉字的方法

http://blog.csdn.net/qmhball/article/details/45690017

 

最近在开发微信自定义菜单。
接口比较简单,就是按微信要求的格式post一段json数据过去就成。
但我的菜单中里有中文,json_encode后出现了类似"\u5c0f\u8c61" 的unicode字符。
请求发出后被微信接口告知:
[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. {"errcode":40033,"errmsg":"invalid charset. please check your request, if include \\uxxxx will create fail!"}  
不支持unicode字符!
那么如何才能使json_encode不转义汉字呢?
方法1
如果你的php版本是5.4+, 那么恭喜你,一个参数JSON_UNESCAPED_UNICODE就能搞定。
[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <?php                                                                                           
  2. $data = array(                                                                                  
  3.     "name"=>"羊羊羊",                                                                           
  4.     "type"=>"view",                                                                             
  5.     "url"=>"http://xuan9806.com/"                                                               
  6. );                                                                                              
  7.                                                                                                 
  8. echo json_encode($data, JSON_UNESCAPED_UNICODE), "\n";    
得到结果
[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. {"name":"羊羊羊","type":"view","url":"http:\/\/xuan9806.com\/"}  

方法2
如果不幸由于种种原因你的php无法升到高版本,那么可以这么做:
把字段中的中文urlencode, 在json_encode后将得到的字串整体urldecode即可
[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. <?php  
  2. $data = array(  
  3.     "name"=>urlencode("羊羊羊"),  
  4.     "type"=>"view",  
  5.     "url"=>"http://xuan9806.com/"  
  6. );  
  7.   
  8. $result = json_encode($data);  
  9. $result = urldecode($result);  
  10.   
  11. echo $result, "\n";  
同样得到法1中的结果。

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值