php json_encode實現(xiàn)與中文亂碼解決方法
來源:程序員人生 發(fā)布時間:2014-05-06 06:33:14 閱讀次數(shù):2693次
php 中使用 json_encode() 內(nèi)置函數(shù)(php > 5.2)可以使用得 php 中數(shù)據(jù)可以與其它語言很好的傳遞并且使用它,這個函數(shù)的功能是將數(shù)值轉(zhuǎn)換成json數(shù)據(jù)存儲格式.
- $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
- echo json_encode($arr);
-
-
下面看一款json_encode中文亂碼問題:
解決方法是用urlencode()函數(shù)處理以下,在json_encode之前,把所有數(shù)組內(nèi)所有內(nèi)容都用urlencode()處理一下,然用json_encode()轉(zhuǎn)換成json字符串,最后再用urldecode()將編碼過的中文轉(zhuǎn)回來.
- 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--;
- }
-
-
-
-
-
-
-
-
-
- function json($array) {
- arrayrecursive($array, 'urlencode', true);
- $json = json_encode($array);
- return urldecode($json);
- }
- $array = array
- (
- 'name'=>'希亞',
- 'age'=>20
- );
- echo json($array);
應(yīng)用實例:
- $servname="localhost";
- $sqlservname="root";
- $sqlservpws="123456";
- $sqlname="lock1";
- $db=mysql_connect($servname,$sqlservname,$sqlservpws) or die("數(shù)據(jù)庫連接失敗");
- mysql_select_db($sqlname,$db);
- $sql = "select * from t_operater";
- $result =mysql_query($sql);
- $rows = mysql_num_rows($result);
- while($obj = mysql_fetch_object($result))
- {
- $arr[] = $obj;
- }
- echo '({"total":"'.$rows.'","results":'.json_encode($arr).'})';
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進(jìn)行捐贈