SoFunction
Updated on 2025-03-11

Questions about json_decode garbled code and NULL

For details, please see below.

Students who write interfaces should often encounter data format conversion. The two essential functions are json_encode() and json_decode().

There are many main things when using these two functions. Here I will talk about json_decode().

json_decode(): Decodes a JSON-formatted string, accepts a JSON-formatted string and converts it into a PHP variable.

(1) After converting the data into an array, the printing will display NUll:

One reason json_decode only supports utf-8.

iconv('gbk','utf-8', $result_string); Use the iconv function to convert the gbk encoding format written to the utf-8 encoding format to be output. If the original data is in the utf-8 format, this step is not used, otherwise garbled code will appear

Reason 2: json strings must be included in double quotes

str_replace("'", '"', $result_string);//Replace single quotes in json data with double quotes

Reason 3: There cannot be extra commas such as: [1,2,]

Replace with regular, preg_replace('/,\s*([\]}])/m', '$1', $result_string);

(2) After converting the data into an array or converting it to json format data, garbled code will be displayed:

At this time, you need to use urlencode() and urldecode()

The following is my code, which has been tested and worked

if(file_exists($result['save_path'])){
  $contents=file_get_contents($result['save_path']);//Write the contents of a file to the utf-8 format, and the data in the json format is included  //$getcontent = iconv("gbk", "utf-8//ignore",$contents);//If the file is originally in utf-8 format, no conversion is required  $getcontent=str_replace("'", '"',$contents);//Replace single quotient with double quotient  preg_replace('/,\s*([\]}])/m', '$1', $getcontent);// Remove the extra commas  $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));
}

The above content is a question about json_decode garbled code and NULL shared by the editor. I hope it will be helpful to everyone.