PHP 5.2.0+ 內建 JSON 擴展,提供兩大核心函數實現數據互換:
| 函數 | 功能 |
|---|---|
json_encode() | PHP 變量 → JSON 字符串 |
json_decode() | JSON 字符串 → PHP 變量 |
json_last_error() | 獲取最後錯誤代碼 |
json_encode() 詳解string json_encode($value [, $options = 0])
參數:$value 必須為 UTF-8 編碼。$options 為位掩碼,常用常量:
JSON_PRETTY_PRINT:美化輸出(縮進)JSON_UNESCAPED_SLASHES:不轉義斜槓JSON_UNESCAPED_UNICODE:直接輸出中文(PHP 5.4+)JSON_FORCE_OBJECT:強制輸出物件而非陣列$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo json_encode($arr); // {"a":1,"b":2,"c":3}
echo json_encode($arr, JSON_PRETTY_PRINT); // 縮進格式
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', strtotime('8/5/1974 12:20:03'));
echo json_encode($e);
// {"name":"sachin","hobbies":"sports","birthdate":"08/05/1974 12:20:03 pm"}
json_decode() 詳解mixed json_decode($json [, $assoc = false [, $depth = 512 [, $options = 0 ]]])
關鍵參數:
$assoc = true:返回關聯陣列而非 stdClass 物件$depth:遞歸深度限制$options:目前僅支援 JSON_BIGINT_AS_STRING(大整數轉字符串)$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json)); // 物件
var_dump(json_decode($json, true)); // 關聯陣列
null 並置錯誤碼$depthjson_last_error() === JSON_ERROR_NONEJSON_BIGINT_AS_STRING