php中json中文處理功能對于初學者來說是一個比較好用的函數,如果我們直接使用json處理函數來做你會發現中文會變成了null了,如果我們轉換在uft8之后會顯示的是中文的字符編碼了,下面我整理兩個工作中用到的函數,希望對各位有幫助.
例子,代碼如下:
- function encodeConvert($str,$fromCode,$toCode)
- {
- if(strtoupper($toCode) == strtoupper($fromCode)) return $str;
- if(is_string($str)){
- if(function_exists('mb_convert_encoding')){
- return mb_convert_encoding($str,$toCode,$fromCode);
- } //開源軟件:Vevb.com
- else{
- return iconv($fromCode,$toCode,$str);
- }
- }
- elseif(is_array($str)){
- foreach($str as $k=>$v){
- $str[$k] = encodeConvert($v,$fromCode,$toCode);
- }
- return $str;
- }
- return $str;
- }
例子,代碼如下:
- /**************************************************************
- *
- * 將數組轉換為JSON字符串(兼容中文)
- * @param array $array 要轉換的數組
- * @return string 轉換得到的json字符串
- * @access public
- *
- *************************************************************/
- function JSON($array) {
- arrayRecursive($array, 'urlencode', true);
- $json = json_encode($array);
- return urldecode($json);
- }
- /**************************************************************
- *
- * 使用特定function對數組中所有元素做處理
- * @param string &$array 要處理的字符串
- * @param string $function 要執行的函數
- * @return boolean $apply_to_keys_also 是否也應用到key上
- * @access public
- *
- *************************************************************/
- function arrayRecursive(&$array, $function, $apply_to_keys_also = false){
- static $recursive_counter = 0;
- if (++$recursive_counter > 1000) {
- die('possible deep recursion attack');
- }
- foreach ($array as $key => $value) {
- if (is_array($value)) {
- arrayRecursive($array[$key], $function, $apply_to_keys_also);
- } else {
- $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]);
- }
- }
- }
- $recursive_counter--;
- }
測試例子,代碼如下:
- $arr = array (
- array (
- 'catid' => '4',
- 'catname' => 'php粉絲網網',
- 'meta_title' => 'php粉絲網網2'
- ),
- array (
- 'catid' => '55',
- 'catname' => 'php教程',
- 'meta_title' => 'http://www.companysz.com',
- )
- );
- echo JSON($arr);
- echo json_encode(encodeConvert($arr,'gb2312','utf-8'));/* */
- 輸出結果如下
- [{"catid":"4","catname":"php粉絲網","meta_title":"php粉絲網2"},{"catid":"55","catname":"php教程","meta_title":"http://www.companysz.com"}]
- [{"catid":"4","catname":"\u4e00\u805a\u6559\u7a0b\u7f51","meta_title":"\u4e00\u805a\u6559\u7a0b\u7f512"},{"catid":"55","catname":"php\u6559\u7a0b","meta_title":"http:\/\/www.companysz.com"}]
|
新聞熱點
疑難解答