欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php操作JSON格式數(shù)據(jù)的實(shí)現(xiàn)代碼

 更新時(shí)間:2011年12月24日 03:24:10   作者:  
php操作JSON格式數(shù)據(jù)的實(shí)現(xiàn)代碼,需要的朋友可以參考下。
知識(shí)點(diǎn):
1、JSON數(shù)據(jù)格式介紹
2、對數(shù)據(jù)編碼成JSON格式
3、對JSON數(shù)據(jù)進(jìn)行解碼,并操作
JSON數(shù)據(jù)格式表示方式如下:
復(fù)制代碼 代碼如下:

{ "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將數(shù)據(jù)編碼成JSON格式:
復(fù)制代碼 代碼如下:

<?php
//php中用數(shù)組表示JSON格式數(shù)據(jù)
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', '非誠'),
'lastname' => iconv('gb2312', 'utf-8', '勿擾'),
'contact' => array(
'email' =>'fcwr@jb51.net',
'website' =>'http://www.dbjr.com.cn',
)
);
//將數(shù)組編碼成JSON數(shù)據(jù)格式
$json_string = json_encode($arr);
//JSON格式數(shù)據(jù)可直接輸出
echo $json_string;
?>

需要指出的是,在非UTF-8編碼下,中文字符將不可被encode,結(jié)果會(huì)出來空值,所以,如果你使用 gb2312編寫PHP代碼,那么就需要將包含中文的內(nèi)容使用iconv或者mb轉(zhuǎn)為UTF-8再進(jìn)行json_encode。
輸出:(JSON格式)
{"firstname":"\u975e\u8bda","lastname":"\u52ff\u6270","contact":{"email":"fcwr@jb51.net","website":"http:\/\/www.dbjr.com.cn"}}
用php對JSON數(shù)據(jù)進(jìn)行解碼并處理:
復(fù)制代碼 代碼如下:

<?php
//php中用數(shù)組表示JSON格式數(shù)據(jù)
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', '非誠'),
'lastname' => iconv('gb2312', 'utf-8', '勿擾'),
'contact' => array(
'email' =>'fcwr@jb51.net',
'website' =>'http://www.dbjr.com.cn',
)
);
//將數(shù)組編碼成JSON數(shù)據(jù)格式
$json_string = json_encode($arr);
//將JSON格式數(shù)據(jù)進(jìn)行解碼,解碼后不是JSON數(shù)據(jù)格式,不可用echo直接輸出
$obj = json_decode($json_string);
//強(qiáng)制轉(zhuǎn)化為數(shù)組格式
$arr = (array) $obj;
//按數(shù)組方式調(diào)用里面的數(shù)據(jù)
echo iconv('utf-8','gb2312',$arr['firstname']);
echo '</br>';
//輸出數(shù)組結(jié)構(gòu)
print_r($arr);
?>

輸出:
非誠
Array ( [firstname] => 闈炶瘹 [lastname] => 鍕挎壈 [contact] => stdClass Object ( [email] => fcwr@jb51.net [website] => http://www.dbjr.com.cn ) )

相關(guān)文章

最新評論