代码之家  ›  专栏  ›  技术社区  ›  dreftymac

与旧PHP版本兼容的PHP json处理程序

  •  2
  • dreftymac  · 技术社区  · 16 年前

    是否有一个通用的PHP JSON库,用于检测您的PHP版本中的JSON支持级别,并在未找到本机支持时调用外部提供的JSON库。。。或者,我会自己花时间写这篇文章吗。

    4 回复  |  直到 16 年前
        1
  •  2
  •   Matt user129975    16 年前

    Facebook在其PHP库中包含一个。希望他们不会介意你借用它:

    http://svn.facebook.com/svnroot/platform/clients/php/trunk/jsonwrapper/

        2
  •  2
  •   Mitch C    16 年前

    /**
         * json_encode2()
         * 
         * @access public
         * @param bool $a
         * @return string
         */
        public function json_encode2($a=false) {
            if (is_null($a)) return 'null';
            if ($a === false) return 'false';
            if ($a === true) return 'true';
            if (is_scalar($a))
            {
              if (is_float($a))
              {
                // Always use "." for floats.
                return floatval(str_replace(",", ".", strval($a)));
              }
    
              if (is_string($a))
              {
                static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
                return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
              }
              else
                return $a;
            }
            $isList = true;
            for ($i = 0, reset($a); $i < count($a); $i++, next($a))
            {
              if (key($a) !== $i)
              {
                $isList = false;
                break;
              }
            }
            $result = array();
            if ($isList)
            {
              foreach ($a as $v) $result[] = $this->json_encode2($v);
              return '[' . join(',', $result) . ']';
            }
            else
            {
              foreach ($a as $k => $v) $result[] = $this->json_encode2($k).':'.$this->json_encode2($v);
              return '{' . join(',', $result) . '}';
            }
        }
    
        3
  •  1
  •   Pekka    16 年前

    我认为这很简单,PHP<5.2.0=没有JSON。有PECL JSON库(JSON函数在集成到PHP中之前的化身),但也没有多大用处。

    你也可以检查一下 function_exists("json_decode") .

    here 对于编码部分。不过,我不知道他们有多可靠。

        4
  •  0
  •   fire    16 年前

    我用了这个:

    $data = array();
    $q = mysql_query("SELECT * FROM blah");
    while ($r = mysql_fetch_array($q, MYSQL_ASSOC)) {
        foreach ($r as $value) $data[] = '"' . addslashes($value) . '"';
    }
    
    echo '['.implode(', ', $data).']';
    

    推荐文章