php中json_encode UTF-8中文亂碼的更好解決方案_php技巧

來源:互聯網
上載者:User

最近在介面代碼當中用到過json_encode,在網上找到說json_encode編碼設定為UTF-8中文就不會亂碼,經驗證這辦法確實是有效果的,但是不知道為什麼,代碼在用過一段時間之後就不太管用了。以下是自己的解決json_encode的辦法。有更好的方法請分享出來吧!

第一種:

這種簡單的做一個代碼轉換,urlcode之後再返回所需數組

我代碼這樣就足夠了。

代碼如下 複製代碼

public static function encodeOperations ($array){foreach ((array)$array as $key => $value) {if (is_array($value)) {encodeOperations($array[$key]);} else {$array[$key] = urlencode(mb_convert_encoding($value,'UTF-8','GBK'));}}return $array;}

第二種:

這種是在網上看到的,然後就是有評論說會出現無限迴圈的問題,但是這顯然很全面的,然後我測試之後也確實有,貼這裡僅供參考

代碼如下

/**************************************************************** 使用特定function對數組中所有元素做處理* @param string &$array 要處理的字串* @param string $tocode 編碼後* @param string $oldcode 編碼前* @param string $function 要執行的函數* @return boolean $apply_to_keys_also 是否也應用到key上* @return array $array 是否也應用到key上* @access public**************************************************************/function encodeOperations (&$array, $function, $tocode=false,$oldcode=false,$apply_to_keys_also = false){foreach ($array as $key => $value) {(www.jb51.net)if (is_array($value)) {encodeOperations($array[$key], $function, $apply_to_keys_also);} else {if($tocode&&$oldcode) {if(function_exists(mb_convert_encoding)) {$value = mb_convert_encoding($value,$tocode,$oldcode);}else{return "error";}}$array[$key] = $function($value);}if ($apply_to_keys_also && is_string($key)) {$new_key = $function($key);if ($new_key != $key) {$array[$new_key] = $array[$key];unset($array[$key]);}}}return $array;}/****from:http://www.jb51.net/phper/31/66729.htm************************************************************ 將數群組轉換為JSON字串(相容中文)* @param array $array 要轉換的數組* @return string 轉換得到的json字串* @access public**************************************************************/function JSON($array) {arrayRecursive($array, 'urlencode', true);$json = json_encode($array);return urldecode($json);}

對中文返回是null空的話我們需要進行字元轉換成uft8或者先使用urlencode進行編譯呼。

PS:關於json操作,這裡再為大家推薦幾款比較實用的json線上工具供大家參考使用:

線上JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.jb51.net/code/json

JSON線上格式化工具:
http://tools.jb51.net/code/jsonformat

線上XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson

json代碼線上格式化/美化/壓縮/編輯/轉換工具:
http://tools.jb51.net/code/jsoncodeformat

線上json壓縮/轉義工具:

http://tools.jb51.net/code/json_yasuo_trans

C語言風格/HTML/CSS/json代碼格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.