Due to the display effect of some special characters, we had to change the used UTF-8 project to GBK. Because of the ajax technology, it also involved the old problem-encoding conversion. Some form verification needs to return json data. php's json_encode function only supports UTF-8 encoding, but only iconv is needed. The effect required is that the GBK array is converted into a UTF-8 array and passed to the json_encode function.
The idea is to serialize the array and use the iconv function to convert and encode it, And then deserialize it. The Code is as follows:
Copy codeThe Code is as follows:
Unserialize (iconv ('gbk', 'utf-8', serialize ($ array )));
The result is blank. Later I remembered that the default encoding ini_set ('default _ charset', 'gbk') was set in the configuration file '); in this way, the UTF-8 string deserialization with gbk is definitely not useful. Here, an ini_set ('default _ charset', 'utf-8') is added between serialization and deserialization '); it should also be possible, but it always seems a bit awkward, because it is a global encoding setting, it is easy to cause Encoding Problems in other places, such as database operations. In another way, the final function is as follows:
Copy codeThe Code is as follows:
Function array_iconv ($ in_charset, $ out_charset, $ arr ){
Return eval ('Return '. iconv ($ in_charset, $ out_charset, var_export ($ arr, true ).';'));
}
The principle is 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 execute the return (similar to the anonymous function ?), This is a perfect solution.
Follow-up: I searched the materials on the Internet to see if there are any better methods. The methods are similar. They all use recursive call of iconv. If there are too many array elements or more dimensions, performance is definitely not good. It is better to use native code. It does not need to be considered whether it is an n-dimensional array or an associated array. Everything has been completed automatically to ensure data consistency before and after array conversion. From the comparison of the code length and the cycle with the native method, I believe everyone has a choice.