您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php操作JSON格式数据的实现代码_PHP

2025/9/17 23:58:58发布21次查看
json
知识点:
1、json数据格式介绍
2、对数据编码成json格式
3、对json数据进行解码,并操作
json数据格式表示方式如下:
复制代码 代码如下:
{ 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 }
] }
用php将数据编码成json格式:
复制代码 代码如下:
iconv('gb2312', 'utf-8', '非诚'),
'lastname' => iconv('gb2312', 'utf-8', '勿扰'),
'contact' => array(
'email' =>'fcwr@bitscn.com',
'website' =>'http://www.bitscn.com',
)
);
//将数组编码成json数据格式
$json_string = json_encode($arr);
//json格式数据可直接输出
echo $json_string;
?>
需要指出的是,在非utf-8编码下,中文字符将不可被encode,结果会出来空值,所以,如果你使用 gb2312编写php代码,那么就需要将包含中文的内容使用iconv或者mb转为utf-8再进行json_encode。
输出:(json格式)
{firstname:\u975e\u8bda,lastname:\u52ff\u6270,contact:{email:fcwr@bitscn.com,website:http:\/\/www.bitscn.com}}
用php对json数据进行解码并处理:
复制代码 代码如下:
iconv('gb2312', 'utf-8', '非诚'),
'lastname' => iconv('gb2312', 'utf-8', '勿扰'),
'contact' => array(
'email' =>'fcwr@bitscn.com',
'website' =>'http://www.bitscn.com',
)
);
//将数组编码成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);
?>
输出:
非诚
array ( [firstname] => 闈炶瘹 [lastname] => 鍕挎壈 [contact] => stdclass object ( [email] => fcwr@bitscn.com [website] => http://www.bitscn.com ) )
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product