Jsondecode contains Chinese garbled characters and returns null. Many friends have encountered this problem. How can this problem be solved? The solutions below are shared on the script home website. For details, refer to the following.
Users who write interfaces should frequently encounter data format conversion. At this time, two essential functions are json_encode () and json_decode ().
These two functions have many main issues. Here I will talk about json_decode ().
Json_decode (): decodes a JSON string, accepts a JSON string, and converts it to a PHP variable.
(1) After the data is converted into an array, the print will display NUll:
One of the reasons is that json_decode only supports UTF-8.
Iconv ('gbk', 'utf-8', $ result_string); Use the iconv function to convert the gbk encoding format of the data to the UTF-8 encoding format to be output, if the original data is in UTF-8 format, skip this step. Otherwise, garbled characters will appear.
Cause 2: The json string must contain double quotation marks.
Str_replace ("'",' "', $ result_string); // Replace the single quotes in json data with double quotes.
Cause 3: there cannot be redundant commas, for example, [,]
Replace with regular expressions, preg_replace ('/, \ s * ([\]}])/m',' $ 1', $ result_string );
(2) garbled characters are displayed after data is converted to an array or json format:
Urlencode () and urldecode () are used at this time ()
The following is my code, which has been tested and valid:
If (file_exists ($ result ['Save _ path']) {$ contents = file_get_contents ($ result ['Save _ path']); // write the content of a file. The file is in UTF-8 format and contains json data // $ getcontent = iconv ("gbk", "UTF-8 // ignore ", $ contents); // if the file is originally in UTF-8 format, you do not need to convert $ getcontent = str_replace ("'",' "', $ contents ); // replace a single quote with a double quote preg_replace ('/, \ s * ([\]}])/m',' $ 1', $ getcontent ); // remove unnecessary 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 small series of questions about json_decode garbled characters and NULL. I hope to help you.