Home >Backend Development >PHP Tutorial >Implementation code for operating json format data conversion in PHP_PHP tutorial

Implementation code for operating json format data conversion in PHP_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-13 16:55:42922browse

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631658.htmlTechArticleThis article mainly introduces the json format data conversion program in php. We use json_decode() and json_encode () These two functions are much more convenient to operate. Friends who need to learn...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn