PHP中JSON处理详解:编码、解码及兼容性问题
如今,JSON已演变为最广泛采用的数据交换格式,绝大多数网站的API接口均对其提供支持。
此前曾撰文探讨过其设计哲学,此处重点梳理PHP语言对JSON的支持机制,这是构建互联网应用尤其是开发API时的必备技能。
自5.2版本起,PHP原生内置了json_encode()用于编码以及json_decode()用于解码两个核心函数。
一、json_encode()函数详解
该函数主要用于将PHP数组或对象转换为JSON格式字符串。首先观察一个数组转换的具体示例:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
执行后的输出结果为:
{"a":1,"b":2,"c":3,"d":4,"e":5}
接着查看一个对象转换的示例:
$obj->body = 'another post';
$obj->id = 21;
$obj->approved = true;
$obj->favorite_count = 1;
$obj->status = NULL;
echo json_encode($obj);
对应的输出结果为:
{
"body":"another post",
"id":21,
"approved":true,
"favorite_count":1,
"status":null
}
鉴于JSON规范仅接受UTF-8编码字符,json_encode()的输入参数必须为UTF-8编码,否则可能返回空字符串或null。当处理GB2312编码的中文或ISO-8859-1编码的外文时,务必注意此编码限制。
二、索引数组与关联数组的区别
PHP包含两种数组类型:仅保存值(value)的索引数组(indexed array),以及保存名值对(name/value)的关联数组(associative array)。
因JavaScript不支持关联数组概念,json_encode()会将索引数组转换为JSON数组格式,而将关联数组转换为JSON对象格式。
例如,定义如下索引数组:
$arr = Array('one', 'two', 'three');
echo json_encode($arr);
转换结果为:
["one","two","three"]
若将其修改为关联数组:
$arr = Array('1'=>'one', '2'=>'two', '3'=>'three');
echo json_encode($arr);
结果结构发生变化:
{"1":"one","2":"two","3":"three"}
需注意,数据格式已从方括号“[]”(数组)变为花括号“{}”(对象)。
若需强制将索引数组转换为对象,可采用以下写法:
json_encode( (object)$arr );
或者使用常量选项:
json_encode ( $arr, JSON_FORCE_OBJECT );
三、类(class)对象的转换规则
考虑以下PHP类定义:
class Foo {
const ERROR_CODE = '404';
public $public_ex = 'this is public';
private $private_ex = 'this is private!';
protected $protected_ex = 'this should be protected';
public function getErrorCode() {
return self::ERROR_CODE;
}
}
对该类的实例进行JSON转换操作:
$foo = new Foo;
$foo_json = json_encode($foo);
echo $foo_json;
最终输出结果为:
{"public_ex":"this is public"}
由此可见,除了公开变量(public)外,其他成员如常量、私有变量及方法等均会被丢弃。
四、json_decode()函数解析
该函数负责将JSON文本还原为相应的PHP数据结构。示例如下:
$json = '{"foo": 12345}';
$obj = json_decode($json);
print $obj->{'foo'}; // 12345
默认情况下,json_decode()返回的是PHP对象而非数组。例如:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
生成的结果是一个PHP对象:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
若希望强制生成PHP关联数组,需向json_decode()传入第二个参数true:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));
此时结果变为关联数组:
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
五、json_decode()常见错误排查
以下三种JSON写法均为非法,请识别其中的错误:
$bad_json = "{ 'bar': 'baz' }";
$bad_json = '{ bar: "baz" }';
$bad_json = '{ "bar": "baz", }';
对上述字符串执行json_decode()均会返回null并触发报错。
第一个错误在于JSON分隔符仅限双引号,不可使用单引号;第二个错误是键名(冒号左侧部分)在任何情况下都必须使用双引号包裹;第三个错误是最后一个值后严禁添加逗号(trailing comma)。
此外,JSON仅适用于表示对象和数组,若对普通字符串或数值调用json_decode(),将直接返回null。
var_dump(json_decode("Hello World")); //null
接下来介绍PHP语言的JSON底层实现方案
在开发ajax file manager for web开源项目时,由于数据交互采用JSON格式,发现在低版本PHP环境中运行异常。经调试确认,原因是低版本PHP未实现json_decode和json_encode函数。为确保兼容性,自行编写了一套PHP版JSON编解码代码,并与json2.js保持行为一致,经测试验证无误,现公布供有相同需求的开发者参考:
<?php
/* * ****************************************************************************
* $base: $
*
* $Author: $
* Berlin Qin
*
* $History: base.js $
* Berlin Qin // created
*
* $contacted
* webfmt@gmail.com
* www.webfmt.com
*
* *************************************************************************** */
/* ===========================================================================
* license
*
* 、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.
*
* 、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 year of personal e-mail support.
*
* ************************************************************************************************************************************************* */
function jsonDecode($json)
{
$result = array();
try
{
if (PHP_VERSION_ID > )
{
$result = (array) json_decode($json);
}
else
{
$json = str_replace(array("\\\\", "\\\""), array("&#;", "&#;"), $json);
$parts = preg_split("@(\"[^\"]*\")|([\[\]\{\},:])|\s@is", $json, -, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $index => $part)
{
if (strlen($part) == )
{
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("&#;", "&#;", "$"), 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 > )
{
$result = json_encode($arr);
}
else
{
$parts = array();
$is_list = false;
if (!is_array($arr))
{
$arr = (array) $arr;
}
$end = count($arr) - ;
if (count($arr) > )
{
if (is_numeric(key($arr)))
{
$result = "[";
for ($i = ; $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 = ;
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;
}
?>
使用过程中如遇任何问题,欢迎发送邮件联系。亦恳请指出代码中的不足之处!