Home >Backend Development >PHP Tutorial >Implementation code for operating json format data conversion in PHP_PHP tutorial
This article mainly introduces the operation of json format data conversion program in php. We use the two functions json_decode() and json_encode() to make the operation much more convenient. Friends who need to learn can refer to this example.
In the first step, we use the json_encode() function to convert the data into json data
代码如下 | 复制代码 |
//php中用数组表示JSON格式数据 $arr = array( 'firstname' => iconv('gb2312', 'utf-8', '非诚'), 'lastname' => iconv('gb2312', 'utf-8', '勿扰'), 'contact' => array( 'email' =>'fcwr@bKjia.c0m', 'website' =>'http://www.bKjia.c0m', ) ); //将数组编码成JSON数据格式 $json_string = json_encode($arr); //JSON格式数据可直接输出 echo $json_string; ?> |
This conversion function only supports utf-8 format. If there are Chinese characters in the middle, you can use iconv or mb to convert to UTF-8 and then json_encode, so there will be no problems.
In the second step, we also use a php json processing function json_decode() to parse the data. The code is as follows
代码如下 | 复制代码 |
//php中用数组表示JSON格式数据 $arr = array( 'firstname' => iconv('gb2312', 'utf-8', '非诚'), 'lastname' => iconv('gb2312', 'utf-8', '勿扰'), 'contact' => array( 'email' =>'fcwr@bKjia.c0m', 'website' =>'http://www.bKjia.c0m', ) ); //将数组编码成JSON数据格式 $json_string = json_encode($arr); //将JSON格式数据进行解码,解码后不是JSON数据格式,不可用echo直接输出 $obj = json_decode($json_string); //强制转化为数组格式 $arr = (array) $obj; //按数组方式调用里面的数据 echo iconv('utf-8','gb2312',$arr['firstname']); echo ''; //输出数组结构 print_r($arr); ?> |
Okay, that’s it for the examples. About
json_decode() reference http://www.bKjia.c0m/phper/18/32827.htm
json_encode() reference http://www.bKjia.c0m/phper/18/32827.htm