PHP JSON編碼後,中文亂碼的解決方式

1,有些時候,須要寫接口,傳遞一些中文值,那麼JSON編碼,會出現目前如下兩種狀況!php

    a.輸出亂碼算法

<?php
    $testJSON=array('name'=>'中文字符串','value'=>'test');  
    echo json_encode($testJSON);  
?> 
輸出結果:{「name」:」\u4e2d\u6587\u5b57\u7b26\u4e32″,」value」:」test」}

    b.不輸出亂碼json

    使用UTF8編碼的字符,使用json_encode也出現了中文亂碼。解決辦法是在使用json_encode以前把字符用數組

    函數urlencode()處理一下,而後再json_encode,輸出結果的時候在用函數urldecode()轉回來。具體以下:函數

<?php  
    $testJSON=array('name'=>'中文字符串','value'=>'test');  
    //echo json_encode($testJSON);  
    $testJSON=ReturnUrlencode($testJSON);


	/**
	 * [ReturnUrlencode 用遞歸的方式來遍歷全部的數組而且解析]
	 * @param [type] $arr [description]
	 */
	function ReturnUrlencode($arr){
		foreach ($arr as $key => $value){
			if(is_array($value)){	
				$arr[$key]=ReturnUrlencode($value);
			}else{
				$arr[$key]=urlencode($value);
			}
		}
		return $arr;
	}

    print_r(urldecode ( json_encode ( $testJSON ) ) );  
?> 
輸出結果:{「name」:」中文字符串」,」value」:」test」}

 遍歷遞歸算法!將數組中的全部值,urlencode!編碼

相關文章
相關標籤/搜索