本章節我們將為大家介紹如何使用 PHP 語言來編碼和解碼 JSON 對象。
在 php5.2.0 及以上版本已經內置 JSON 擴展。
PHP json_encode() 用於對變量進行 JSON 編碼,該函數如果執行成功返回 JSON 數據,否則返回 FALSE 。
string json_encode ( $value [, $options = 0 ] )
以下實例演示了如何將 PHP 數組轉換為 JSON 格式數據:
<?php
$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}
以下實例演示了如何將 PHP 對象轉換為 JSON 格式數據:
<?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);
?>
以上代碼執行結果為:
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
PHP json_decode() 函數用於對 JSON 格式的字符串進行解碼,並轉換為 PHP 變量。
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
json_string: 待解碼的 JSON 字符串,必須是 UTF-8 編碼數據
assoc: 當該參數為 TRUE 時,將返回數組,FALSE 時返回對象。
depth: 整數類型的參數,它指定遞歸深度
options: 二進制掩碼,目前只支持 JSON_BIGINT_AS_STRING 。
以下實例演示了如何解碼 JSON 數據:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
以上代碼執行結果為:
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)
}