本文章主要是介绍了在 php 中操作 json 格式数据转换程序, 我们利用了 json_decode() 和 json_encode() 这两个函数来进行操作方便很多, 有需要学习的朋友可以参考一下本实例
第一步我们利用 json_encode() 函数把数据转换成 json 数据
- //php 中用数组表示 JSON 格式数据 <br ow="0" oh="0">$arr = array(
- 'firstname' => iconv('gb2312', 'utf-8', '非诚'),
- 'lastname' => iconv('gb2312', 'utf-8', '勿扰'),
- 'contact' => array(
- 'email' =>'fcwr@phprm.com',
- 'website' =>'http://www.phprm.com',
- )
- );
- // 将数组编码成 JSON 数据格式 <br ow="0" oh="0">$json_string = json_encode($arr);
- //JSON 格式数据可直接输出 <br ow="0" oh="0">echo $json_string;
- ?>
此转换函数只支持 utf-8 格式的如果中间有中文可以利用 iconv 或者 mb 转为 UTF-8 再进行 json_encode, 这样就不会有任何问题
第二步, 对数据进行解析我们也用一个 php json 处理函数 json_decode() 了, 代码如下
代码如下
- //php 中用数组表示 JSON 格式数据 <br ow="0" oh="0">$arr = array(
- 'firstname' => iconv('gb2312', 'utf-8', '非诚'),
- 'lastname' => iconv('gb2312', 'utf-8', '勿扰'),
- 'contact' => array(
- 'email' =>'fcwr@phprm.com',
- 'website' =>'http://www.phprm.com',
- )
- );
- // 将数组编码成 JSON 数据格式 <br ow="0" oh="0">$json_string = json_encode($arr);
- // 将 JSON 格式数据进行解码, 解码后不是 JSON 数据格式, 不可用 echo 直接输出 <br ow="0" oh="0">$obj = json_decode($json_string);
- // 强制转化为数组格式 <br ow="0" oh="0">$arr = (array) $obj;
- // 按数组方式调用里面的数据 <br ow="0" oh="0">echo iconv('utf-8','gb2312',$arr['firstname']);
- echo '';
- // 输出数组结构 <br ow="0" oh="0">print_r($arr);
- ?>
来源: https://www.php1.cn/detail/php-f984667417.html