Home > Web Front-end > JS Tutorial > body text

Problems with json_decode garbled characters and NULL_javascript skills

WBOY
Release: 2016-05-16 15:36:38
Original
1532 people have browsed it

具体内容请看下文吧。

写接口的同学应该会经常遇到数据格式的转换,这时候必不可少的两个函数就是json_encode()和json_decode()。

这两个函数使用的时候有很多的主要事项,在这里我来说一下json_decode()。

json_decode(): 对JSON 格式的字符串进行解码,接受一个JSON 格式的字符串并且把它转换为 PHP 变量。

(1)将数据转换成数组之后,打印会显示NUll:

原因之一json_decode只支持utf-8.

iconv('gbk','utf-8', $result_string);用iconv函数将写入数据的gbk编码格式转换为要输出的utf-8编码格式,若原本的数据是utf-8格式,则不用此步骤,否则还会出现乱码

原因之二:json字符串必须以双引号包含

str_replace("'", '"', $result_string);//将json数据中的单引替换成双引

原因之三:不能有多余的逗号 如:[1,2,]

用正则替换掉,preg_replace('/,\s*([\]}])/m', '$1', $result_string);

(2)将数据转换成数组或者在转换成json格式数据之后,会显示乱码:

这时候要用到urlencode()和urldecode()

以下是我的代码,经试验有效

if(file_exists($result['save_path'])){
  $contents=file_get_contents($result['save_path']);//将一个文件的内容写入,文件是utf-8格式,里面是json格式的数据
  //$getcontent = iconv("gbk", "utf-8//ignore",$contents);//若文件原本是utf-8格式,无需转换
  $getcontent=str_replace("'", '"',$contents);//将单引替换成双引
  preg_replace('/,\s*([\]}])/m', '$1', $getcontent);//去掉多余的逗号
  $new_array=array();
  $new_array=json_decode($getcontent,true);
  $res=array();
  foreach ($new_array as $key=>$val){
   foreach ($new_array[$key]['items'] as $k=>$v){
    if($k<$row){
     $res[$k]['position']=$v['position'];
     $res[$k]['distance']=$v['distance'];
     $res[$k]['title']=urlencode($v['title']);
     $res[$k['vicinity']=urlencode($v['vicinity']);
    }
   }
  }
 if($res){
 $new_res['items']=$res;
 }else{
 $new_res['items']="";
 }
 echo urldecode(json_encode($new_res));
}
Copy after login

以上内容是小编给大家分享的有关json_decode乱码及NULL的问题,希望对大家有所帮助。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!