Knowledge Points:
1, JSON data format introduction
2. Encode the data into JSON format
3, the JSON data decoding, and operation
The JSON data format is represented in the following ways:
Copy Code code 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 in PHP:
Copy Code code as follows:
<?php
PHP uses arrays to represent JSON-formatted data
$arr = Array (
' FirstName ' => iconv (' gb2312 ', ' utf-8 ', ' not honest '),
' LastName ' => iconv (' gb2312 ', ' utf-8 ', ' Don't Disturb '),
' Contact ' => Array (
' Email ' => ' fcwr@jb51.net ',
' website ' => ' http://www.jb51.net ',
)
);
Encode an array as a JSON data format
$json _string = Json_encode ($arr);
JSON format data can be directly output
echo $json _string;
?>
It should be pointed out that, in the UTF-8 encoding, the Chinese characters will not be encode, the result will come out null value, so if you use gb2312 to write PHP code, then you need to use Iconv or MB content to UTF-8 and then Json_encode.
Output: (JSON format)
{"FirstName": "\u975e\u8bda", "LastName": "\u52ff\u6270", "contact": {"email": "Fcwr@jb51.net", "website": "http:\/\/ Www.jb51.net "}}
Use PHP to decode and process JSON data:
Copy Code code as follows:
<?php
PHP uses arrays to represent JSON-formatted data
$arr = Array (
' FirstName ' => iconv (' gb2312 ', ' utf-8 ', ' not honest '),
' LastName ' => iconv (' gb2312 ', ' utf-8 ', ' Don't Disturb '),
' Contact ' => Array (
' Email ' => ' fcwr@jb51.net ',
' website ' => ' http://www.jb51.net ',
)
);
Encode an array as a JSON data format
$json _string = Json_encode ($arr);
Decode JSON format data, not JSON data format, no direct output with Echo
$obj = Json_decode ($json _string);
Force conversion to array format
$arr = (array) $obj;
Call the data inside by array
echo iconv (' Utf-8 ', ' gb2312 ', $arr [' FirstName ']);
Echo ' </br> ';
Output array Structure
Print_r ($arr);
?>
Output:
Non-Prudential
Array ([FirstName] => 闈 Undercover 瘹 [LastName] => 鍕 slung stevioside [contact] => stdClass Object ([email] => fcwr@jb51.net [website] => http://www.jb51.net))