如何让PHP v5.2 之前的版本中使用 JSON (json_encode和decode)
方法一:
/**
* 替换JSON方法
*/
if (!function_exists("json_encode")) {
include_once("JSON.php");
function json_encode($array) {
$json = new Services_JSON();
$json_array = $json->encode($array);
return $json_array;
}
/**
* 解析JSON数据
* @param string $json_data 需要解析的JSON数据
* @param bool $toarray 是否需要解析成数组
* @return array 返回解析后的数组
*/
function json_decode($json_data, $toarray = TRUE) {
$json = new Services_JSON();
$array = $json->decode($json_data);
if ($toarray) { // 需要转换成数组
$array = object2array($array);
}
return $array;
}
}
JSON.php的文件下载链接
或方法二:
<?php
if (!function_exists(’json_encode’))
{
function json_encode($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("\", "/", "
", " ", "
", "", "", ’"’), 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[] = json_encode($v);
return ’[’ . join(’,’, $result) . ’]’;
}
else
{
foreach ($a as $k => $v) $result[] = json_encode($k).’:’.json_encode($v);
return ’{’ . join(’,’, $result) . ’}’;
}
}
}
if ( !function_exists(’json_decode’) ){
function json_decode($json)
{
// Author: walidator.info 2009
$comment = false;
$out = ’$x=’;
for ($i=0; $i<strlen($json); $i++)
{
if (!$comment)
{
if ($json[$i] == ’{’) $out .= ’ array(’;
else if ($json[$i] == ’}’) $out .= ’)’;
else if ($json[$i] == ’:’) $out .= ’=>’;
else $out .= $json[$i];
}
else $out .= $json[$i];
if ($json[$i] == ’"’) $comment = !$comment;
}
eval($out . ’;’);
return $x;
}
}
?>
loading