W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
本章節(jié)我們將為大家介紹如何使用 PHP 語言來編碼和解碼 JSON 對(duì)象。
在 php5.2.0 及以上版本已經(jīng)內(nèi)置 JSON 擴(kuò)展。
函數(shù) | 描述 |
---|---|
json_encode | 對(duì)變量進(jìn)行 JSON 編碼 |
json_decode | 對(duì) JSON 格式的字符串進(jìn)行解碼,轉(zhuǎn)換為 PHP 變量 |
json_last_error | 返回最后發(fā)生的錯(cuò)誤 |
PHP json_encode() 用于對(duì)變量進(jìn)行 JSON 編碼,該函數(shù)如果執(zhí)行成功返回 JSON 數(shù)據(jù),否則返回 FALSE 。
string json_encode ( $value [, $options = 0 ] )
以下實(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"}
PHP json_decode() 函數(shù)用于對(duì) JSON 格式的字符串進(jìn)行解碼,并轉(zhuǎn)換為 PHP 變量。
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
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í)例演示了如何解碼 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)
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: