public function printjson($data, $jsoncallback = '', $fromcode = "utf-8")
{
mb_convert_variables("utf8", $fromcode, $data);
//ajax通過設定access-control-allow-origin來實作跨域通路比較簡單.指定允許其他域名通路
header('access-control-allow-origin:*');
header("cache-control: no-cache, no-store, must-revalidate, max-age=-1");
header("content-type: application/json; charset=utf-8");
$output = function_exists('json_encode') ? json_encode($data) : cjson::encode($data);
if ('' != $jsoncallback) {
$output = $jsoncallback . '(' . $output . ')';
}
echo $output;
yii::app()->end();
}
如果json字元串的key缺少雙引括起來,則json_decode會失敗,判斷是否存在缺少雙引括起來的key,如缺少則先用正則替換為"key",再進行json_decode操作
<?php
/** 相容key沒有雙引括起來的json字元串解析
* @param string $str json字元串
* @param boolean $mod true:array,false:object
* @return array/object
*/
function ext_json_decode($str, $mode=false){
if(preg_match('/\w:/', $str)){
$str = preg_replace('/(\w+):/is', '"$1":', $str);
}
return json_decode($str, $mode);
$str1 = '{name:"fdipzone"}';
var_dump(ext_json_decode($str1, true)); // array(1) { ["name"]=> string(8) "fdipzone" }
?>
json隻支援 utf-8 編碼,所有用header
/**************************************************************
*
* 使用特定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--;
* 将數組轉換為json字元串(相容中文)
* @param array $array 要轉換的數組
* @return string 轉換得到的json字元串
function json($array) {
arrayrecursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
$array = array(
'name' => '希亞',
'age' => 20
);
header("cache-control: no-cache, no-store, must-revalidate, max-age=-1");
header("content-type: application/json; charset=utf-8");
echo json($array);
echo "<br/>";
print_r(json_decode(json($array)));
echo "<br/>------default------<br/>";
$tt = json_encode($array);
print_r($tt);
exit(json_decode($tt));
{"name":"希亞","age":"20"}
stdclass object ( [name] => 希亞 [age] => 20 )
------default------
{"name":"\u5e0c\u4e9a","age":20}
stdclass object ( [name] => 希亞 [age] => 20 )
列印json_decode結果 json_decode加了true參數會傳回關聯數組,否則出現stdclass object對象