大家都知道Ajax,並對它都不陌生,現在就說說json在php的應用,php5.2開始內置了對json的支持,主要用到的兩個函數:json_encode()和json_decode(),一個編碼,一個解碼
< ?php
$arr = array(
'name' => '張三',
'nick' => '深空',
'contact' => array(
'email' => 'shenkong at qq dot com',
'website' => 'http://www.chenyixin.com',
)
);
$json_string = json_encode($arr);
//有編碼就有解碼:$json_string=json_decode($arr);
echo $json_string;
?>
注意:這是在編碼爲UTF-8的時候,如果爲gb2312,需要用iconv和mb轉爲UTF-8在進行json_encode()
結果輸出:
{"name":"\u9648\u6bc5\u946b","nick":"\u6df1\u7a7a","contact":
{"email":"shenkong at qq dot com","website":"http:\/\/www.chenyixin.com"}}