Because some special character's display effect reason had to change the custom Utf-8 project to the GBK, because uses the AJAX technology, also involves the old problem--the coding transformation. Some form validation needs to return JSON data, PHP's Json_encode function only supports UTF-8 encoding, but only iconv, the effect that needs to be achieved is to convert GBK array to utf-8 function.
The first idea is to serialize the array, convert the encoding with the ICONV function, and then deserialize the code as follows:
Copy Code code as follows:
Unserialize (Iconv (' GBK ', ' Utf-8 ', serialize ($array));
The resulting results are blank, and later remembered to configure the default encoding Ini_set (' default_charset ', ' GBK ') in the config file; It is certainly not good to deserialize the Utf-8 string with GBK, where a ini_set (' Default_charset ', ' utf-8 ') is added between serialization and deserialization; It should be OK, but it always feels a bit awkward, because it is the global coding setting that can easily lead to coding problems elsewhere, such as database operations. So, in a different way, using the serialization method of building array prototypes, with the help of the Var_export function, the final function is as follows:
Copy Code code as follows:
function Array_iconv ($in _charset, $out _charset, $arr) {
Return eval (iconv ($in _charset, $out _charset,var_export ($arr, True).
}
The principle is simple. Var_export sets the second argument to True, returns the array prototype string, converts the string to Utf-8 encoding, and then executes the return with eval (similar to an anonymous function?). ), to solve the problem perfectly.
Follow-up: Later on the internet to search the information, see if there is a better way to find all the same, are using recursive call Iconv way, if the array elements too much or more than a few dimensions, performance is certainly not how, better is the way of native code, do not need to consider is an n-dimensional array or associative array, Everything has been done automatically to ensure that the data is consistent before and after the array conversion. From the length of the code and the comparison of the cycle and the native method, I believe we have a choice.