json只接受utf-8編碼的字符,所以php的函數json_encode()的參數必須是utf-8編碼
==========json格式:
============== ================
錯誤的json格式:
$error_json = "{ 'name': 'jack' }"; //json的分隔符只允許使用雙引號,不能使用單引號$error_json = '{ name: "jack" }'; //json鍵值對的"鍵"(冒號左邊的部分),必須使用雙引號
$error_json = ' { "name": "baz", }'; //最後一個值之後不能加逗號
========================= ====
正確的json格式
$yes_json= '{"name":"jack"}';
PHPcode. )函數:將數組和對象,轉換為json格式
例如:
①將鍵/值對數組轉為json格式,將變成對象形式的json
『 'a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);echo "json化後arr為:".json_encode($ arr); ============================================== ==== json化後arr為:{"a":1,"b":2,"c":3,"d":4,"e":5}
②將索引數組轉為json格式,將變成陣列形式的json
echo json_encode$arr); =========================================== ["one"," two","three"]
將索引數組強制轉換成物件:
json_encode( (object)$arr );
③將類別的物件轉換為json格式,只保留public的欄位
const ERROR_CODE = '404'public const ERROR_CODE = '404'public const ERROR_CODE = '404'public] 〜〜〴 private $private_var = 'this is private_var'; protected $protected_var = 'this is protected_var';
public function getErr〕} }
============== ==========================
$ClassA = new ClassA;
$classA_json = json_encode($ClassA);
echo $classA_json ;
========================================
{"public_var":"this is public_var"}
(2).json_decode()函數,將json格式的字串轉換為php變量,預設轉為object物件,當傳入第二個參數為true時,轉為true為php陣列
例如:
①.轉為php物件
$json = '{"a":1,"b":2,"c":3,"d":1,"b":2,"c":3,"d":1,"b":2,"c":3,"d":1,"b":2,"c":3,"d":1,"b":2,"c":3,"d":1,"b":2,"c":3,"d" 4,"e":5}var_dump($json);
================================== ===========object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2)
["c "] => int(3)["d"] => int(4) ["e"] => int(5) }
②.轉為php陣列= '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));
== ===========================================
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
[" e"] => int(5) }
以上就介紹了PHP操作json,包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。