Knowledge points:
1. Introduction to JSON data format
2. Encode data into JSON format
3. Decode JSON data and operate
The JSON data format is represented as follows:
Copy code The 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" }
] }
Use php to encode the data into JSON format:
Copy the code The code is as follows:
//Use arrays to represent JSON format data in php
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', 'Feicheng'),
'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 output directly
echo $json_string;
?>
It should be pointed out that in non-UTF-8 Under encoding, Chinese characters will not be encoded, and the result will be a null value. Therefore, if you use gb2312 to write PHP code, you need to use iconv or mb to convert the content containing Chinese to UTF-8 and then perform json_encode.
Output: (JSON format)
{"firstname":"u975eu8bda","lastname":"u52ffu6270","contact":{"email":"fcwr@jb51.net","website": "http://www.jb51.net"}}
Use php to decode and process JSON data:
Copy code The code is as follows:
//Use array to represent JSON format data in php
$arr = array(
'firstname' => iconv('gb2312', 'utf -8', 'Not sincere'),
'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);
//Decode the JSON format data. The decoded data is not in JSON data format and cannot be output directly with echo
$obj = json_decode ($json_string);
//Forced conversion to array format
$arr = (array) $obj;
//Call the data in array format
echo iconv('utf-8' ,'gb2312',$arr['firstname']);
echo '';
//Output array structure
print_r($arr);
?>
Output:
Feicheng
Array ( [firstname] => => fcwr@jb51.net [website] => http://www.jb51.net ) )
http://www.bkjia.com/PHPjc/324624.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324624.htmlTechArticleKnowledge points: 1. Introduction to JSON data format 2. Encoding data into JSON format 3. Decoding JSON data , and operate the JSON data format representation as follows: Copy the code The code is as follows: {...