由於JSON可以在多種程式語言中使用,所以我們可以用來做小型資料中轉,如:PHP輸出JSON字串供JavaScript使用等。在PHP中可以使用 json_decode() 由一串規範的字串解析出 JSON對象,使用 json_encode() 由JSON 物件產生一串規範的字串。
例:
$json = '{"a":1, "b":2, "c":3, "d":4, "e":5 }';
var_dump(json_decode($json));
var_dump(json_decode($json,true));
輸出:
["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)
}
echo json_encode($arr);
輸出:
{"a":1,"b":2,"c":3,"d":4,"e":5}
1. json_decode(),字元轉JSON,一般用在接收到Javascript 發送的資料時會用到。$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf @163.com","xx":"xxxxxxx"}}';$web=json_decode($s);
2. json_encode(),JSON轉字符,這個一般在AJAX 應用中,為了將JSON對象轉化成字符串並輸出給 Javascript 時會用到,而向數據庫中存儲時也會用到。
$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf @163.com","xx":"xxxxxxx"}}';$web=json_decode($s);
$s='{"webname":"homehf","url":"www.homehf.com","qq":"744348666"}';$web=json_decode($s) ; //將字元轉成JSON
$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf @163.com","xx":"xxxxxxx"}}';$web=json_decode($s);