Knowledge point:
1. Introduction to JSON data formats
2. encode data in JSON format
3. decodes and operates JSON data.
The JSON data format is as follows:
Copy codeThe Code is as follows:
{"Programmers ":[
{"FirstName": "Brett", "lastName": "McLaughlin", "email": "aaaa "},
{"FirstName": "Jason", "lastName": "Hunter", "email": "bbbb "},
{"FirstName": "Elliotte", "lastName": "Harold", "email": "cccc "}
],
"Authors ":[
{"FirstName": "Isaac", "lastName": "Asimov", "genre": "science fiction "},
{"FirstName": "Tad", "lastName": "Williams", "genre": "fantasy "},
{"FirstName": "Frank", "lastName": "Peretti", "genre": "christian fiction "}
],
"Musicians ":[
{"FirstName": "Eric", "lastName": "Clapton", "instrument": "guitar "},
{"FirstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano "}
]}
Encode data into JSON format using php:
Copy codeThe Code is as follows:
<? Php
// JSON format data is represented by arrays in php.
$ Arr = array (
'Firstname' => iconv ('gb2312', 'utf-8', 'sincerity '),
'Lastname' => iconv ('gb2312', 'utf-8', 'Do not disturb '),
'Contact '=> array (
'Email '=> 'fcwr @ jb51.net ',
'Website' => 'HTTP: // www.jb51.net ',
)
);
// Encode the array into JSON Data Format
$ Json_string = json_encode ($ arr );
// JSON format data can be directly output
Echo $ json_string;
?>
It should be noted that, in non-UTF-8 encoding, Chinese characters will not be encode, the results will be null, So if you use gb2312 to write PHP code, then we need to use iconv or mb to convert the content containing Chinese characters into UTF-8 and then perform json_encode.
Output: (JSON format)
{"Firstname": "\ u975e \ u8133", "lastname": "\ u52ff \ u6270", "contact": {"email": "fcwr@jb51.net", "website ": "http: \/www.jb51.net "}}
Use php to decode and process JSON data:
Copy codeThe Code is as follows:
<? Php
// JSON format data is represented by arrays in php.
$ Arr = array (
'Firstname' => iconv ('gb2312', 'utf-8', 'sincerity '),
'Lastname' => iconv ('gb2312', 'utf-8', 'Do not disturb '),
'Contact '=> array (
'Email '=> 'fcwr @ jb51.net ',
'Website' => 'HTTP: // www.jb51.net ',
)
);
// Encode the array into JSON Data Format
$ Json_string = json_encode ($ arr );
// Decodes JSON data. The decoded data is not in JSON format and cannot be output directly using echo.
$ Obj = json_decode ($ json_string );
// Forcibly convert to array format
$ Arr = (array) $ obj;
// Call the data in the array
Echo iconv ('utf-8', 'gb2312', $ arr ['firstname']);
Echo '</br> ';
// Output Array Structure
Print_r ($ arr );
?>
Output:
FEICHENG
Array ([firstname] => too many objects [lastname] => too many objects [contact] => stdClass Object ([email] => fcwr@jb51.net [website] => http://www.jb51.net ))