知識點:
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格式:
復制代碼 代碼如下:
<?php
//php中用數組表示JSON格式數據
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', '非誠'),
'lastname' => iconv('gb2312', 'utf-8', '勿擾'),
'contact' => array(
'email' =>'
[email protected]',
'website' =>'http://www.jb51.net',
)
);
//將數組編碼成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":"
[email protected]","website":"http:\/\/www.jb51.net"}}
用php對JSON數據進行解碼並處理:
復制代碼 代碼如下:
<?php
//php中用數組表示JSON格式數據
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', '非誠'),
'lastname' => iconv('gb2312', 'utf-8', '勿擾'),
'contact' => array(
'email' =>'
[email protected]',
'website' =>'http://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 '</br>';
//輸出數組結構
print_r($arr);
?>
輸出:
非誠
Array ( [firstname] => 闈炶瘹 [lastname] => 鍕挎壈 [contact] => stdClass Object ( [email] =>
[email protected] [website] => http://www.jb51.net ) )