- 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();
- }
- <?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" }
- ?>
- <?php
- /**************************************************************
- *
- * 使用特定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字符串
- * @access public
- *
- *************************************************************/
- 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);
- echo "<br/>";
- 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对象