本章節(jié)我們將為大家介紹如何使用 PHP 語言來編碼和解碼 JSON 對(duì)象。
環(huán)境配置
在 php5.2.0 及以上版本已經(jīng)內(nèi)置 JSON 擴(kuò)展。
JSON 函數(shù)
函數(shù) | 描述 |
---|---|
json_encode | 對(duì)變量進(jìn)行 JSON 編碼 |
json_decode | 對(duì) JSON 格式的字符串進(jìn)行解碼,轉(zhuǎn)換為 PHP 變量 |
json_last_error | 返回最后發(fā)生的錯(cuò)誤 |
json_encode
PHP json_encode() 用于對(duì)變量進(jìn)行 JSON 編碼,該函數(shù)如果執(zhí)行成功返回 JSON 數(shù)據(jù),否則返回 FALSE 。
語法
string json_encode ( $value [, $options = 0 ] )
參數(shù)
value: 要編碼的值。該函數(shù)只對(duì) UTF-8 編碼的數(shù)據(jù)有效。
options:由以下常量組成的二進(jìn)制掩碼:JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
實(shí)例
以下實(shí)例演示了如何將 PHP 數(shù)組轉(zhuǎn)換為 JSON 格式數(shù)據(jù):
<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr); ?>以上代碼執(zhí)行結(jié)果為:
{"a":1,"b":2,"c":3,"d":4,"e":5}以下實(shí)例演示了如何將 PHP 對(duì)象轉(zhuǎn)換為 JSON 格式數(shù)據(jù):
<?php class Emp { public $name = ""; public $hobbies = ""; public $birthdate = ""; } $e = new Emp(); $e->name = "sachin"; $e->hobbies = "sports"; $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p"); $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03")); echo json_encode($e); ?>以上代碼執(zhí)行結(jié)果為:
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
json_decode
PHP json_decode() 函數(shù)用于對(duì) JSON 格式的字符串進(jìn)行解碼,并轉(zhuǎn)換為 PHP 變量。
語法
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
參數(shù)
json_string: 待解碼的 JSON 字符串,必須是 UTF-8 編碼數(shù)據(jù)
assoc: 當(dāng)該參數(shù)為 TRUE 時(shí),將返回?cái)?shù)組,F(xiàn)ALSE 時(shí)返回對(duì)象。
depth: 整數(shù)類型的參數(shù),它指定遞歸深度
options: 二進(jìn)制掩碼,目前只支持 JSON_BIGINT_AS_STRING 。
實(shí)例
以下實(shí)例演示了如何解碼 JSON 數(shù)據(jù):
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true)); ?>以上代碼執(zhí)行結(jié)果為:
object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) } array(5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) }