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

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

最近在开发微信自定义菜单。
接口比较简单,就是按微信要求的格式post一段json数据过去就成。
但我的菜单中里有中文,json_encode后出现了类似"u5c0fu8c61" 的unicode字符。
请求发出后被微信接口告知:
[plain] view plaincopy在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 plaincopy在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), " ";    
得到结果
[plain] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. {"name":"羊羊羊","type":"view","url":"http://xuan9806.com/"}  

方法2
如果不幸由于种种原因你的php无法升到高版本,那么可以这么做:
把字段中的中文urlencode, 在json_encode后将得到的字串整体urldecode即可
[php] view plaincopy在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, " ";  
同样得到法1中的结果。
 
原文地址:https://www.cnblogs.com/lixiuran/p/4861300.html