PHP操作JSON数据的核心知识点
核心知识点包括以下三个方面:
首先了解JSON数据的基本格式规范;
其次掌握如何将PHP数据结构编码为JSON格式;
最后学习如何对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格式的方法如下:
<?php //在PHP中使用数组来表示即将转换为JSON的数据
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', '非诚'),
'lastname' => iconv('gb2312', 'utf-8', '勿扰'),
'contact' => array(
'email' =>'fcwr@jb51.net',
'website' =>'https://www.jb51.net',
)
); //将上述数组编码为JSON数据格式
$json_string = json_encode($arr);
//JSON格式数据可以直接输出
echo $json_string;
?> 需要注意的是,如果PHP脚本运行在非UTF-8编码环境下,中文字符将无法被正确encode,导致结果为空值。因此,若使用gb2312编写PHP代码,必须先将包含中文的内容通过iconv或mb_convert_encoding函数转换为UTF-8编码,然后再调用json_encode。
输出结果(JSON格式):
{"firstname":"\u975e\u8bda","lastname":"\u52ff\u6270","contact":{"email":"fcwr@jb51.net","website":"http:\/\/www.jb51.net"}}
在PHP中对JSON数据进行解码并处理的步骤如下:
<?php //在PHP中使用数组来表示原始数据
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', '非诚'),
'lastname' => iconv('gb2312', 'utf-8', '勿扰'),
'contact' => array(
'email' =>'fcwr@jb51.net',
'website' =>'https://www.jb51.net',
)
); //将数组编码成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@jb51.net [website] => https://www.jb51.net ) )