php操作JSON格式資料的實現代碼

來源:互聯網
上載者:User

知識點:
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' =>'fcwr@jb51.net',
'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":"fcwr@jb51.net","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' =>'fcwr@jb51.net',
'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] => fcwr@jb51.net [website] => http://www.jb51.net ) )

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.