Json is often used as a data exchange format, which is more bulky than xml.
Json is often used as a data exchange format, which is more bulky than xml.
Starting from version 5.2, PHP provides native json_encode () and json_decode () functions. The former is used for encoding and the latter is used for decoding.
Json_encode ()
This function is mainly used to convert arrays and objects into json format.
The Code is as follows:
$ Arr = array ('A' => 'A', 'B' => 'B', 'C' = 'C', 'D' => 'D ', 'E' = 'E ');
Echo json_encode ($ arr );
Output result:
Json only accepts UTF-8 encoded characters. The json_encode () parameter must be UTF-8 encoded.
Class person {public $ name; public $ age; public $ height; function _ construct ($ name, $ age, $ height) {$ this-> name = $ name; $ this-> age = $ age; $ this-> height = $ height ;}}$ obj = new person ("zhangsan", 20,100 ); $ foo_json = json_encode ($ obj); echo $ foo_json;
Output result:
When the attribute in the class is a private variable, it is not output.
Json_decode ()
This function is used to convert json text to the corresponding PHP data structure.
The Code is as follows:
$ Json = '{"a": "hello", "B": "world", "c": "zhangsan", "d": 20, "e ": 170 }';
Var_dump (json_decode ($ json ));
Output result:
In general, json_decode () always returns a PHP Object.
Convert to an array:
The Code is as follows:
$ Json = '{"a": "hello", "B": "world", "c": "zhangsan", "d": 20, "e ": 170 }';
Var_dump (json_decode ($ json, ture ));
The above is all the content of this article. I hope you will like it.