Due to the display effect of some special characters, I had to change the customary UTF-8 project to GBK. Due to the use of Ajax technology, it also involves an old problem - encoding conversion. Some form verification needs to return json data. PHP's json_encode function only supports utf-8 encoding, so I have no choice but to iconv. The desired effect is to convert the GBK array into a utf-8 array and pass it to the json_encode function.
The initial idea is to serialize the array and use the iconv function to convert the encoding, and then deserialize it. The code is as follows:
The result obtained was blank. Later I remembered that the default encoding ini_set('default_charset', 'gbk'); was set in the configuration file. It is definitely not easy to use gbk to deserialize utf-8 strings. Here It should also be possible to add ini_set('default_charset', 'utf-8'); between serialization and deserialization, but it always feels a bit awkward to do this because it is a global encoding setting, which can easily lead to errors in other places. Coding issues, such as database operations. Then change your mind and use the serialization method of constructing the array prototype, with the help of the var_export function, the final function is as follows:
The principle is very simple. var_export sets the second parameter to true, returns the array prototype string, converts the string to utf-8 encoding, and then uses eval to perform the return (similar to an anonymous function?), which solves the problem perfectly.
Follow-up: Later, I searched for information on the Internet to see if there was a better method. All I found were similar. They all used recursive calls to iconv. If the array has too many elements or more dimensions, the performance will definitely not be good. What's going on? What's better is the native code method. There is no need to consider whether it is an N-dimensional array or an associative array. Everything has been completed automatically to ensure that the data is consistent before and after the array conversion. Judging from the length of the code and the comparison between loops and native methods, I believe everyone already has a choice.