PHP JSON
JSON?? ??????
· JSON? JavaScript Object Notation(JavaScript Object Notation)? ?????.
· JSON? ?? ??? ??? ?? ?????.
· JSON? ?? ??????. *
· JSON? ?? ????? ???? ????
* JSON? JavaScript ??? ???? ??? ??? ????? JSON? ??? ???? ? ??? ??????. JSON ??? JSON ?????? ??? ????? ??? ?????.
????
? php5.2.0? ???????. ??.JSON ??.
JSON ??
?
| ?>< ??>???>?> | ||||||||
json_encode | ? ??? JSON?? ??????. | ||||||||
json_decode | JSON ??? ??? PHP ??? ?? | ||||||||
json_last_error | ??? ???? ???? ?? |
json_encode
json_encode()? JSON ??? ??? ?????. ? ??? ????? ???? JSON ???? ????, ??? ??? FALSE? ?????.
??
json_encode ($value,[,options = 0 ] )
????
· value : ???? ????. ? ??? UTF-8? ???? ????? ?????.
· ??: ?? ??? ??? ???? ???: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT,
JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
· ?? json? UTF? ?????. -8 ??? ?????? json_encode()? ????? UTF-8? ?????? ???. ??? ??? ? ?? ?? null? ?????. ???? GB2312 ???? ????? ???? ISO-8859-1 ???? ???? ?? ?? ??? ??? ???? ???.
?
?? ?? 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('Y-m-d h:i:s a', "2016/9/19 12:20:03 p"); $e->birthdate = date('Y-m-d h:i:s a', strtotime("2016/9/19 12:20:03")); echo json_encode($e); ?>
???? ?? ??:
{"??":"??","??":"???","??":"2016-09-19 ?? 12:20:03"} $json [,$assoc = false [, $length = 512 [, $options = 0 ]]]
json_decode
json_decode() ??? JSON ?? ???? ????? ?? PHP ??? ???? ? ?????.
??
json_decode ($json [,$assoc = false [, $length = 512 [, $ options = 0 ]]])
????
· json_string: ???? JSON ???? UTF-8? ???? ????? ???
·?assoc: ? ????? TRUE?? ??? ????, FALSE?? ??? ?????.
· ??: ?? ??? ???? ?? ?? ????
· ??: ???? ???, ?? JSON_BIGINT_AS_STRING? ?????.
json_decode() ?? ??
?? ? ?? json ?? ??? ?? ?? ??? ??????
$bad_json = "{ 'bar': 'baz' }";
$bad_json = '{ bar: "baz" }';$bad_json = '{ "bar": "baz", }';
? ? ???? ?? json_decode()? ???? null? ???? ??? ?????.
? ?? ??? json ?? ??? ?????? ?? ????? ????? ????.
? ?? ??? json ??-? ?? "??"(?? ?? ??)? ?? ???? ????? ???? ??? ????.
? ?? ??? ??? ? ?? ??? ??? ? ??? ????.
?? json? ?? ? ??? ???? ??? ??? ? ????. json_decode()? ????? ?? ???? null? ?????.
?
?? ?? 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(5)}array(5) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> " ]=> int(4) ["e"]=> int(5)}