免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3007 | 回复: 3
打印 上一主题 下一主题

用php实现json编码与解码(原创) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-10-15 17:14 |只看该作者 |倒序浏览
本帖最后由 lanneret_sky 于 2011-10-15 17:26 编辑

由于开发一个ajax file manager for web开源项目,数据交换使用的json格式,后来发现在低版本的php上运行会有问题,仔细调试发现json_decode和json_encode无法正常工作,于是查阅资料,发现低版本的php没有实现这两个函数,为了兼容性,我只好自己实现一个php版的json编码解码代码,并保证和 json2.js的一致,测试调试并通过,现在将其公布出来,供有相同需求的同学使用:
  1.     <?php
  2.     /* * ****************************************************************************
  3.      * $base: $
  4.      *
  5.      * $Author: $
  6.      *         Berlin Qin
  7.      *
  8.      * $History: base.js $
  9.      * Berlin Qin 2011/5/15 created
  10.      *
  11.      * $contacted
  12.      * webfmt@gmail.com
  13.      * http://www.webfmt.com
  14.      *
  15.      * *************************************************************************** */
  16.     /* ===========================================================================
  17.      * license
  18.      *
  19.      * You may not use this file except in compliance with the License.
  20.      * Software distributed under the License is distributed on an "AS IS" basis,
  21.      *   WITHOUT WARRANTY OF ANY KIND, either express or implied,except that you announce  what to you write.

  22.      * The Initial Developer of the Original Code is Berlin Qin.
  23.     Copyright (C) 2000-2050, Berlin Qin., All Rights Reserved.
  24.      *
  25.      *************************************************************************/
  26.     function jsonDecode($json)
  27.     {
  28.         $result = array();
  29.         try
  30.         {
  31.             if (PHP_VERSION_ID > 50300)
  32.             {
  33.                 $result = (array) json_decode($json);
  34.             }
  35.             else
  36.             {
  37.                 $json = str_replace(array("\\\\", "\\\""), array("\", """), $json);
  38.                 $parts = preg_split("@(\"[^\"]*\")|([\[\]\{\},:])|\s@is", $json, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
  39.                 foreach ($parts as $index => $part)
  40.                 {
  41.                     if (strlen($part) == 1)
  42.                     {
  43.                         switch ($part)
  44.                         {
  45.                             case "[":
  46.                             case "{":
  47.                                 $parts[$index] = "array(";
  48.                                 break;
  49.                             case "]":
  50.                             case "}":
  51.                                 $parts[$index] = ")";
  52.                                 break;
  53.                             case ":":
  54.                                 $parts[$index] = "=>";
  55.                                 break;
  56.                             case ",":
  57.                                 break;
  58.                             default:
  59.                                 break;
  60.                         }
  61.                     }
  62.                 }
  63.                 $json = str_replace(array("\", """, "$"), array("\\\\", "\\\"", "\\$"), implode("", $parts));
  64.                 $result = eval("return $json;");
  65.             }
  66.         }
  67.         catch (Exception $e)
  68.         {
  69.             $result = array("error" => $e->getCode());
  70.         }
  71.         return $result;
  72.     }
  73.     function valueTostr($val)
  74.     {
  75.         if (is_string($val))
  76.         {
  77.             $val = str_replace('\"', "\\\"", $val);
  78.             $val = str_replace("\\", "\\\\", $val);
  79.             $val = str_replace("/", "\\/", $val);
  80.             $val = str_replace("\t", "\\t", $val);
  81.             $val = str_replace("\n", "\\n", $val);
  82.             $val = str_replace("\r", "\\r", $val);
  83.             $val = str_replace("\b", "\\b", $val);
  84.             $val = str_replace("\f", "\\f", $val);
  85.             return '"' . $val . '"';
  86.         }
  87.         elseif (is_int($val))
  88.             return sprintf('%d', $val);
  89.         elseif (is_float($val))
  90.             return sprintf('%F', $val);
  91.         elseif (is_bool($val))
  92.             return ($val ? 'true' : 'false');
  93.         else
  94.             return 'null';
  95.     }
  96.     function jsonEncode($arr)
  97.     {
  98.         $result = "{}";
  99.         try
  100.         {
  101.             if (PHP_VERSION_ID > 50300)
  102.             {
  103.                 $result = json_encode($arr);
  104.             }
  105.             else
  106.             {
  107.                 $parts = array();
  108.                 $is_list = false;
  109.                 if (!is_array($arr))
  110.                 {
  111.                     $arr = (array) $arr;
  112.                 }
  113.                 $end = count($arr) - 1;
  114.                 if (count($arr) > 0)
  115.                 {
  116.                     if (is_numeric(key($arr)))
  117.                     {
  118.                         $result = "[";
  119.                         for ($i = 0; $i < count($arr); $i++)
  120.                         {
  121.                             if (is_array($arr[$i]))
  122.                             {
  123.                                 $result = $result . jsonEncode($arr[$i]);
  124.                             }
  125.                             else
  126.                             {
  127.                                 $result = $result . valueTostr($arr[$i]);
  128.                             }
  129.                             if ($i != $end)
  130.                             {
  131.                                 $result = $result . ",";
  132.                             }
  133.                         }
  134.                         $result = $result . "]";
  135.                     }
  136.                     else
  137.                     {
  138.                         $result = "{";
  139.                         $i = 0;
  140.                         foreach ($arr as $key => $value)
  141.                         {
  142.                             $result = $result . '"' . $key . '":';
  143.                             if (is_array($value))
  144.                             {
  145.                                 $result = $result . jsonEncode($value);
  146.                             }
  147.                             else
  148.                             {
  149.                                 $result = $result . valueTostr($value);
  150.                             }
  151.                             if ($i != $end)
  152.                             {
  153.                                 $result = $result . ",";
  154.                             }
  155.                             $i++;
  156.                         }
  157.                         $result = $result . "}";
  158.                     }
  159.                 }
  160.                 else
  161.                 {
  162.                     $result = "[]";
  163.                 }
  164.             }
  165.         }
  166.         catch (Exception $e)
  167.         {
  168.         }
  169.         return $result;
  170.     }
  171.     ?>
复制代码

论坛徽章:
0
2 [报告]
发表于 2011-10-17 14:40 |只看该作者
费这劲干嘛,直接升级。

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:55:28
3 [报告]
发表于 2011-10-17 14:44 |只看该作者
回复 2# php-kohana


    老系统可不是说升级就升级的。

论坛徽章:
0
4 [报告]
发表于 2011-10-17 20:04 |只看该作者
所以只有用php写一个,保证老的也能用
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP