This article mainly introduces the json format data conversion program in php. We use the json_decode () and json_encode () functions to perform operations conveniently.
This article mainly introduces the json format data conversion program in php. We use the json_decode () and json_encode () functions to perform operations conveniently.
The first step is to use the json_encode () function to convert the data into json data. the code is as follows:
-
- // 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 @ phpfensi.com ',
- 'Website' => 'http: // www.phpfensi.com ',
- )
- );
- // Encode the array into JSON data format
- $ Json_string = json_encode ($ arr );
- // JSON format data can be directly output
- Echo $ json_string;
- ?>
This conversion function only supports UTF-8 format. if there is a Chinese character in the middle, you can use iconv or mb to convert it to the UTF-8 and then perform json_encode, so there will be no problem.
Step 2: parse the data and use a php json processing function json_decode (). The code is as follows:
-
- // 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 @ phpfensi.com ',
- 'Website' => 'http: // www.phpfensi.com ',
- )
- );
- // 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'
';
- // Output array structure
- Print_r ($ arr );
- ?>
Okay, the instance is here.