PHP array encoding: Two Methods for mutual conversion between gbk and utf8:
1. Use the var_export () and eval () Methods
/*** Convert a Chinese array containing GBK into UTF-8 ** @ param array $ arr array * @ param string $ in_charset original string encoding * @ param string $ out_charset output string encoding * @ return array */function array_iconv ($ arr, $ in_charset = "gbk", $ out_charset = "UTF-8") {$ ret = eval ('Return '. iconv ($ in_charset, $ out_charset, var_export ($ arr, true ). ';'); return $ ret; // After transcoding, You can output json // return json_encode ($ ret );}
The principle is simple.var_export
Set the second parametertrue
, Returns the array prototype string, converts the string to UTF-8 encoding, and then useseval
(Like Anonymous functions ?), This is a perfect solution.
Eval () function summary:
Condition:eval()
The function calculates the string according to the PHP code. The string must be a valid PHP code and must end with a semicolon.
If it is not called in the code stringreturn
Statement, then returnNULL
. If a parsing error exists in the codeeval()
The function returns false.
$ A = "hello"; $ res = eval ("return $ a;"); print_r ($ res ); // when assigning values, you must use a backslash to escape the $ identifier eval ("\ $ str = \" $ str \ ";"); echo $ str;
Ii. use recursion to transcode the Array
/*** UTF-8 encoding GBK encoding mutual conversion/(array supported) *** @ param array $ str string, * @ param string $ in_charset original string encoding * @ param string $ out_charset output string encoding * @ return array */function array_iconv ($ str, $ in_charset = "gbk", $ out_charset = "UTF-8") {if (is_array ($ str) {foreach ($ str as $ k => $ v) {$ str [$ k] = array_iconv ($ v);} return $ str;} else {if (is_string ($ str )) {// return iconv ('utf-8', 'gbk // IGNORE ', $ str); return mb_convert_encoding ($ str, $ out_charset, $ in_charset );} else {return $ str ;}}}
Summary
PHP converts the array encoding gbk and UTF-8 to each other. This is basically the end of the article, which is very detailed and has reference value, I hope this article will help you in your study and work.