php过滤掉不乱码json,PHP JSON编码后,中文乱码的解决方式
1,有些時候,需要寫接口,傳遞一些中文值,那么JSON編碼,會出現目前以下兩種情況!
a.輸出亂碼
$testJSON=array('name'=>'中文字符串','value'=>'test');
echo?json_encode($testJSON);
?>
輸出結果:{“name”:”\u4e2d\u6587\u5b57\u7b26\u4e32″,”value”:”test”}
b.不輸出亂碼
使用UTF8編碼的字符,使用json_encode也出現了中文亂碼。解決辦法是在使用json_encode之前把字符用
函數urlencode()處理一下,然后再json_encode,輸出結果的時候在用函數urldecode()轉回來。具體如下:
$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!
總結
以上是生活随笔為你收集整理的php过滤掉不乱码json,PHP JSON编码后,中文乱码的解决方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 复杂电路简化经典例题_【中考物理】电路简
- 下一篇: php 留言板项目 ajax,PHP A