php語(yǔ)言中使用json的技巧及json的實(shí)現(xiàn)代碼詳解
目前,JSON已經(jīng)成為最流行的數(shù)據(jù)交換格式之一,各大網(wǎng)站的API幾乎都支持它。
我寫過(guò)一篇《數(shù)據(jù)類型和JSON格式》,探討它的設(shè)計(jì)思想。今天,我想總結(jié)一下PHP語(yǔ)言對(duì)它的支持,這是開發(fā)互聯(lián)網(wǎng)應(yīng)用程序(特別是編寫API)必須了解的知識(shí)。
從5.2版本開始,PHP原生提供json_encode()和json_decode()函數(shù),前者用于編碼,后者用于解碼。
一、json_encode()
該函數(shù)主要用來(lái)將數(shù)組和對(duì)象,轉(zhuǎn)換為json格式。先看一個(gè)數(shù)組轉(zhuǎn)換的例子:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
結(jié)果為
{"a":1,"b":2,"c":3,"d":4,"e":5}
再看一個(gè)對(duì)象轉(zhuǎn)換的例子:
$obj->body = 'another post'; $obj->id = 21; $obj->approved = true; $obj->favorite_count = 1; $obj->status = NULL; echo json_encode($obj);
結(jié)果為
{
"body":"another post",
"id":21,
"approved":true,
"favorite_count":1,
"status":null
}
由于json只接受utf-8編碼的字符,所以json_encode()的參數(shù)必須是utf-8編碼,否則會(huì)得到空字符或者null。當(dāng)中文使用GB2312編碼,或者外文使用ISO-8859-1編碼的時(shí)候,這一點(diǎn)要特別注意。
二、索引數(shù)組和關(guān)聯(lián)數(shù)組
PHP支持兩種數(shù)組,一種是只保存"值"(value)的索引數(shù)組(indexed array),另一種是保存"名值對(duì)"(name/value)的關(guān)聯(lián)數(shù)組(associative array)。
由于javascript不支持關(guān)聯(lián)數(shù)組,所以json_encode()只將索引數(shù)組(indexed array)轉(zhuǎn)為數(shù)組格式,而將關(guān)聯(lián)數(shù)組(associative array)轉(zhuǎn)為對(duì)象格式。
比如,現(xiàn)在有一個(gè)索引數(shù)組
$arr = Array('one', 'two', 'three');
echo json_encode($arr);
結(jié)果為:
["one","two","three"]
如果將它改為關(guān)聯(lián)數(shù)組:
$arr = Array('1'=>'one', '2'=>'two', '3'=>'three');
echo json_encode($arr);
結(jié)果就變了:
{"1":"one","2":"two","3":"three"}
注意,數(shù)據(jù)格式從"[]"(數(shù)組)變成了"{}"(對(duì)象)。
如果你需要將"索引數(shù)組"強(qiáng)制轉(zhuǎn)化成"對(duì)象",可以這樣寫
json_encode( (object)$arr );
或者
json_encode ( $arr, JSON_FORCE_OBJECT );
三、類(class)的轉(zhuǎn)換
下面是一個(gè)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;
}
}
現(xiàn)在,對(duì)這個(gè)類的實(shí)例進(jìn)行json轉(zhuǎn)換:
$foo = new Foo; $foo_json = json_encode($foo); echo $foo_json;
輸出結(jié)果是
{"public_ex":"this is public"}
可以看到,除了公開變量(public),其他東西(常量、私有變量、方法等等)都遺失了。
四、json_decode()
該函數(shù)用于將json文本轉(zhuǎn)換為相應(yīng)的PHP數(shù)據(jù)結(jié)構(gòu)。下面是一個(gè)例子:
$json = '{"foo": 12345}';
$obj = json_decode($json);
print $obj->{'foo'}; // 12345
通常情況下,json_decode()總是返回一個(gè)PHP對(duì)象,而不是數(shù)組。比如:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
結(jié)果就是生成一個(gè)PHP對(duì)象:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
如果想要強(qiáng)制生成PHP關(guān)聯(lián)數(shù)組,json_decode()需要加一個(gè)參數(shù)true:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));
結(jié)果就生成了一個(gè)關(guān)聯(lián)數(shù)組:
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
五、json_decode()的常見錯(cuò)誤
下面三種json寫法都是錯(cuò)的,你能看出錯(cuò)在哪里嗎?
$bad_json = "{ 'bar': 'baz' }";
$bad_json = '{ bar: "baz" }';
$bad_json = '{ "bar": "baz", }';
對(duì)這三個(gè)字符串執(zhí)行json_decode()都將返回null,并且報(bào)錯(cuò)。
第一個(gè)的錯(cuò)誤是,json的分隔符(delimiter)只允許使用雙引號(hào),不能使用單引號(hào)。第二個(gè)的錯(cuò)誤是,json名值對(duì)的"名"(冒號(hào)左邊的部分),任何情況下都必須使用雙引號(hào)。第三個(gè)的錯(cuò)誤是,最后一個(gè)值之后不能添加逗號(hào)(trailing comma)。
另外,json只能用來(lái)表示對(duì)象(object)和數(shù)組(array),如果對(duì)一個(gè)字符串或數(shù)值使用json_decode(),將會(huì)返回null。
var_dump(json_decode("Hello World")); //null
下面給大家介紹哦php語(yǔ)言的json實(shí)現(xiàn)
由于開發(fā)一個(gè)ajax file manager for web開源項(xiàng)目,數(shù)據(jù)交換使用的json格式,后來(lái)發(fā)現(xiàn)在低版本的php上運(yùn)行會(huì)有問(wèn)題,仔細(xì)調(diào)試發(fā)現(xiàn)json_decode和json_encode無(wú)法正常工作,于是查閱資料,發(fā)現(xiàn)低版本的php沒(méi)有實(shí)現(xiàn)這兩個(gè)函數(shù),為了兼容性,我只好自己實(shí)現(xiàn)一個(gè)php版的json編碼解碼代碼,并保證和json2.js的一致,測(cè)試調(diào)試并通過(guò),現(xiàn)在將其公布出來(lái),供有相同需求的同學(xué)使用:
<?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;
}
?>
如果使用過(guò)程有什么問(wèn)題,可以給我email.歡迎大家指出錯(cuò)誤!
- 使用JSON實(shí)現(xiàn)數(shù)據(jù)的跨域傳輸?shù)膒hp代碼
- php中json_decode()和json_encode()的使用方法
- 使用PHP接收POST數(shù)據(jù),解析json數(shù)據(jù)
- 解析PHP 使用curl提交json格式數(shù)據(jù)
- 如何在php中正確的使用json
- php使用curl發(fā)送json格式數(shù)據(jù)實(shí)例
- php使用json_encode對(duì)變量json編碼
- 教你如何使用PHP輸出中文JSON字符串
- PHP中使用json數(shù)據(jù)格式定義字面量對(duì)象的方法
- PHP使用json_encode函數(shù)時(shí)不轉(zhuǎn)義中文的解決方法
- ThinkPHP中使用ajax接收json數(shù)據(jù)的方法
- php中JSON的使用與轉(zhuǎn)換
相關(guān)文章
YII Framework學(xué)習(xí)之request與response用法(基于CHttpRequest響應(yīng))
這篇文章主要介紹了YII Framework學(xué)習(xí)之request與response用法,詳細(xì)介紹了CHttpRequest響應(yīng)request與response的使用技巧,需要的朋友可以參考下2016-03-03
php微信公眾號(hào)開發(fā)之關(guān)鍵詞回復(fù)
這篇文章主要為大家詳細(xì)介紹了php微信公眾號(hào)開發(fā)之關(guān)鍵詞回復(fù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-10-10
Zend Framework框架Smarty擴(kuò)展實(shí)現(xiàn)方法
這篇文章主要介紹了Zend Framework框架Smarty擴(kuò)展實(shí)現(xiàn)方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Zend Framework框架Smarty擴(kuò)展的具體步驟與相關(guān)設(shè)置技巧,需要的朋友可以參考下2016-03-03
php無(wú)法連接mysql數(shù)據(jù)庫(kù)的正確解決方法
這篇文章主要為大家詳細(xì)介紹了php無(wú)法連接mysql數(shù)據(jù)庫(kù)的正確解決方法,感興趣的小伙伴們可以參考一下2016-07-07
laravel框架關(guān)于搜索功能的實(shí)現(xiàn)
本文是作者整理的關(guān)于laravel框架搜索功能的實(shí)現(xiàn)原理,并附上了詳細(xì)代碼,有需要的小伙伴請(qǐng)持續(xù)關(guān)注!2018-03-03
thinkphp3.2中實(shí)現(xiàn)phpexcel導(dǎo)出帶生成圖片示例
本篇文章主要介紹了thinkphp3.2中實(shí)現(xiàn)phpexcel導(dǎo)出帶生成圖片示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02

