The students who write the interface should often encounter the conversion of the data format, when the essential two functions are Json_encode () and Json_decode ().
These two functions are used when there are a lot of main things, here I say Json_decode ().
Json_decode (): decodes a JSON-formatted string, accepts a JSON-formatted string, and converts it to a PHP variable.
(1) After converting data to an array, 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 of the write data to the Utf-8 encoding format to be output, if the original data is in UTF-8 format, this step is not necessary, otherwise garbled
Note: Using the Iconv function is not PHP's own, you need to be able to modify the php.ini file, will be extension=php_iconv.dll before the ";" Remove and copy the Iconv.dll under your original PHP installation file to your Winnt/system32 (if your DLL is pointing to this directory). (It's possible that the PHP installation file??? )
Reason two:the JSON string must be enclosed in double quotation marks
Str_replace ("'", ' "', $result _string);//Replace single-lead in JSON data with double-lead
Reason three: cannot have extra comma such as: [1, 2,]
Replace with regular, Preg_replace ('/,\s* ([\]}])/M ', ' $ ', $result _string);
(2) after converting data into an array or after converting to JSON format data, garbled characters are displayed:
UrlEncode () and UrlDecode () are used at this time
Here is my code, tested and effective
if (file_exists ($result [' Save_path '])) {
$contents =file_get_contents ($result [' Save_path ']);//writes the contents of a file to the Utf-8 format, which is a JSON-formatted data
$getcontent = Iconv ("GBK", "Utf-8//ignore", $contents);//If the file is originally Utf-8 format, no conversion required
$getcontent =str_replace ("'", ' "', $contents);//Replace single-lead with double-lead
Preg_replace ('/,\s* ([\]}])/M ', ' $ ', $getcontent);//Remove the extra comma
$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));
}
Solution to Json_decode garbled and null