| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx

php语言的json实现

5
PHP JSON C/C++ Go 36992 次浏览
由于开发一个ajax file manager for web开源项目,数据交换使用的json格式,后来发现在低版本的php上运行会有问题,仔细调试发现json_decode和json_encode无法正常工作,于是查阅资料,发现低版本的php没有实现这两个函数,为了兼容性,我只好自己实现一个php版的json编码解码代码,并保证和json2.js的一致,测试调试并通过,现在将其公布出来,供有相同需求的同学使用:
<?php
/* * ****************************************************************************
 * $base: $
 *
 * $Author:  $
 * 		Berlin Qin
 *
 * $History: base.js $
 *      Berlin Qin    2011/5/15         created
 *
 * $contacted
 *      webfmt@gmail.com
 *      www.webfmt.com
 *
 * *************************************************************************** */
/* ===========================================================================
 * license
 *
 * 1、Open Source Licenses
 * webfmt is distributed under the GPL, LGPL and MPL open source licenses.
 * This triple copyleft licensing model avoids incompatibility with other open source licenses.
 * These Open Source licenses are specially indicated for:
 *   Integrating webfmt into Open Source software;
 *   Personal and educational use of webfmt;
 *   Integrating webfmt in commercial software,
 *  taking care of satisfying the Open Source licenses terms,
 *   while not able or interested on supporting webfmt and its development.
 *
 * 2、Commercial License – fbis source Closed Distribution License - CDL
 * For many companies and products, Open Source licenses are not an option.
 * This is why the fbis source Closed Distribution License (CDL) has been introduced.
 * It is a non-copyleft license which gives companies complete freedom
 * when integrating webfmt into their products and web sites.
 * This license offers a very flexible way to integrate webfmt in your commercial application.
 * These are the main advantages it offers over an Open Source license:
 *     Modifications and enhancements doesn't need to be released under an Open Source license;
 *     There is no need to distribute any Open Source license terms alongside with your product
 * and no reference to it have to be done;
 *     No references to webfmt have to be done in any file distributed with your product;
 *     The source code of webfmt doesn’t have to be distributed alongside with your product;
 *     You can remove any file from webfmt when integrating it with your product.
 * The CDL is a lifetime license valid for all releases of webfmt published during
 * and before the year following its purchase.
 * It's valid for webfmt releases also. It includes 1 year of personal e-mail support.
 *
 * ************************************************************************************************************************************************* */

function jsonDecode($json)
{
    $result = array();
    try
    {
        if (PHP_VERSION_ID > 50300)
        {
            $result = (array) json_decode($json);
        }
        else
        {
            $json = str_replace(array("\\\\", "\\\""), array("&#92;", "&#34;"), $json);
            $parts = preg_split("@(\"[^\"]*\")|([\[\]\{\},:])|\s@is", $json, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
            foreach ($parts as $index => $part)
            {
                if (strlen($part) == 1)
                {
                    switch ($part)
                    {
                        case "[":
                        case "{":
                            $parts[$index] = "array(";
                            break;
                        case "]":
                        case "}":
                            $parts[$index] = ")";
                            break;
                        case ":":
                            $parts[$index] = "=>";
                            break;
                        case ",":
                            break;
                        default:
                            break;
                    }
                }
            }
            $json = str_replace(array("&#92;", "&#34;", "$"), array("\\\\", "\\\"", "\\$"), implode("", $parts));
            $result = eval("return $json;");
        }
    }
    catch (Exception $e)
    {
        $result = array("error" => $e->getCode());
    }
    return $result;
}

function valueTostr($val)
{
    if (is_string($val)) 
    {
        $val = str_replace('\"', "\\\"", $val);
        $val = str_replace("\\", "\\\\", $val);
        $val = str_replace("/", "\\/", $val);
        $val = str_replace("\t", "\\t", $val);
        $val = str_replace("\n", "\\n", $val);
        $val = str_replace("\r", "\\r", $val);
        $val = str_replace("\b", "\\b", $val);
        $val = str_replace("\f", "\\f", $val);
        return '"' . $val . '"';
    }
    elseif (is_int($val))
        return sprintf('%d', $val);
    elseif (is_float($val))
        return sprintf('%F', $val);
    elseif (is_bool($val))
        return ($val ? 'true' : 'false');
    else
        return 'null';
}

function jsonEncode($arr)
{
    $result = "{}";
    try
    {
        if (PHP_VERSION_ID > 50300)
        {
            $result = json_encode($arr);
        }
        else
        {
            $parts = array();
            $is_list = false;
            if (!is_array($arr))
            {
                $arr = (array) $arr;
            }
            $end = count($arr) - 1;
            if (count($arr) > 0)
            {
                if (is_numeric(key($arr)))
                {
                    $result = "[";  
                    for ($i = 0; $i < count($arr); $i++)
                    {
                        if (is_array($arr[$i]))
                        {
                            $result = $result . jsonEncode($arr[$i]);
                        }
                        else
                        {
                            $result = $result . valueTostr($arr[$i]);
                        }
                        if ($i != $end)
                        {
                            $result = $result . ",";
                        }
                    }
                    $result = $result . "]";
                }
                else
                {
                    $result = "{"; 
                    $i = 0;
                    foreach ($arr as $key => $value)
                    {
                        $result = $result . '"' . $key . '":';
                        if (is_array($value))
                        {
                            $result = $result . jsonEncode($value);
                        }
                        else
                        {
                            $result = $result . valueTostr($value);
                        }
                        if ($i != $end)
                        {
                            $result = $result . ",";
                        }
                        $i++;
                    }
                    $result = $result . "}";
                }
            }
            else
            {
                $result = "[]";
            }
        }
    }
    catch (Exception $e)
    {

    }
    return $result;
}
?>
如果使用过程有什么问题,可以给我email.欢迎大家指出错误!
来自:http://www.open-open.com/home/space.php?uid=37854&do=blog&id=5014

12个答案

0

looks very creative color blind test

0

We at Nursing Assignments Help understand that plagiarism or copying assignments can vulnerably impact your academia. For this, we have Assignment Writers with a decade of experience. Our expert author works hard to ensure you have sufficient time to examine the work and complete the entire project within a week of submitting it with a sense of professionalism.

0

As only at Assignments Pro, we have highly qualified professional assignment writers. And not just that but we would make sure to provide students with the most incredible help with Assignments Pro. However, it is the same reason why over 1000+ students rely on Assignments Pro. So don’t wait to order PhD Assignments Pro writers from Assignments Pro.

0

Are you studying in the United Kingdom? If yes then you must already be trouble due to dissertations. And not just that but they might just sound like the most troubling thing to deal with. Is this is the case for you? If yes then don’t worry as you are not alone. And that is because almost 12000+ student in the United Kingdom are troubled due to dissertations. And that is because it is rare for students to get successful with their dissertations. This is the reason why over 18000+ students in the United Kingdom need Online Dissertation Writing Services. Are you in the need of the same thing? Well then order it at Dissertations Land.

0
0

How many hours of classes, examine, and printing on paper have you tired out before this time? Countless! Getting near the finishing of an MA assumption to be tested wasn’t easy. Apparently, all those hours tired out fashionable intellectual tumor weren’t enough to lead you to high-quality thesis, either. Do you see reason? No one always annoyed training you in what way or manner to put language down on paper.

You well-informed in what way or manner to write essays and research document. You’ve inscribed many of those task. But the MA paper exist way challenging.

Here’s a hope: reason don’t you use a dissertation aid to help you accompanying the process?

At first, apparently like a outrageous idea. You exist presumed commotion this all by yourself. But when you accomplish that won’t happen, written dissertation help exist the only resolution you’ve receive.

There are two main reasons reason high-quality belief printing on paper service happen a need for MA and PhD job:

  1. Not all person actively learning are famous fashionable academic printed composition. They still be entitled to the degree. Professional assumption to be tested person who composes with language help bureaucracy reach a goal that goal.
  2. The due date maybe intensely bother. When you absolutely can’t complete the paper according to schedule, you need to depend a supporting for help.
0

Free java downloading has been taking place with the efforts and opportunities of the internet for the students. Yes, this has been rightly followed for the thesis writing services to be placed before the people for the right and fundamental instances for the organisms of the current and pertinent planning’s for the people.

0

感谢楼主分享

0
多点中文注释就好了
0
谢谢鼓励!
0

Web File Management Tool (Webfmt) ,文件管理工具. webfmt是一个功能强大的,很容易使用的,很容易和自己系统集成的基于浏览器的ajax file manager,界面和操作都很简单,和在Windows下文件管理基本一致,各类用户能很快掌握其使用方法

webfmt用于对web site文件(包括图片、flashhtml、下载文件等资源)统一管理,实现相同的资源多整个网站共享、共用,避免网站内容资源文件混乱、重复,同时可以更加灵活的实现部署网站内容。

webfmt也可以作为一个文件服务器的管理内核及操作界面。例如:基于webfmt定制一套用户及权限管理系统就可以做成一个nas服务器.

      webfmt是一个安全的文件管理系统。针对文件各种操作提供有自定义处理接口,例如上传文件自动重命名,用户是否登录,哪些类型文件允许上传,上传后对文件的检查等等.
       webfmt在firefox4.0+,chrome12.0+支持多文件选择上传,支持拖拽文件上传。
       webfmt兼容浏览器:ie7.0+,firefox3.5+,chrome12.0+,safari3.5+,opera10.0+.
0
我的开源项目,欢迎大家访问ajax file manager