具體內(nèi)容請(qǐng)看下文吧。
寫(xiě)接口的同學(xué)應(yīng)該會(huì)經(jīng)常遇到數(shù)據(jù)格式的轉(zhuǎn)換,這時(shí)候必不可少的兩個(gè)函數(shù)就是json_encode()和json_decode()。
這兩個(gè)函數(shù)使用的時(shí)候有很多的主要事項(xiàng),在這里我來(lái)說(shuō)一下json_decode()。
json_decode(): 對(duì)JSON 格式的字符串進(jìn)行解碼,接受一個(gè)JSON 格式的字符串并且把它轉(zhuǎn)換為 PHP 變量。
(1)將數(shù)據(jù)轉(zhuǎn)換成數(shù)組之后,打印會(huì)顯示NUll:
原因之一json_decode只支持utf-8.
iconv('gbk','utf-8', $result_string);用iconv函數(shù)將寫(xiě)入數(shù)據(jù)的gbk編碼格式轉(zhuǎn)換為要輸出的utf-8編碼格式,若原本的數(shù)據(jù)是utf-8格式,則不用此步驟,否則還會(huì)出現(xiàn)亂碼
原因之二:json字符串必須以雙引號(hào)包含
str_replace("'", '"', $result_string);//將json數(shù)據(jù)中的單引替換成雙引
原因之三:不能有多余的逗號(hào) 如:[1,2,]
用正則替換掉,preg_replace('/,/s*([/]}])/m', '$1', $result_string);
(2)將數(shù)據(jù)轉(zhuǎn)換成數(shù)組或者在轉(zhuǎn)換成json格式數(shù)據(jù)之后,會(huì)顯示亂碼:
這時(shí)候要用到urlencode()和urldecode()
以下是我的代碼,經(jīng)試驗(yàn)有效
if(file_exists($result['save_path'])){ $contents=file_get_contents($result['save_path']);//將一個(gè)文件的內(nèi)容寫(xiě)入,文件是utf-8格式,里面是json格式的數(shù)據(jù) //$getcontent = iconv("gbk", "utf-8//ignore",$contents);//若文件原本是utf-8格式,無(wú)需轉(zhuǎn)換 $getcontent=str_replace("'", '"',$contents);//將單引替換成雙引 preg_replace('/,/s*([/]}])/m', '$1', $getcontent);//去掉多余的逗號(hào) $new_array=array(); $new_array=json_decode($getcontent,true); $res=array(); foreach ($new_array as $key=>$val){ foreach ($new_array[$key]['items'] as $k=>$v){ if($k<$row){ $res[$k]['position']=$v['position']; $res[$k]['distance']=$v['distance']; $res[$k]['title']=urlencode($v['title']); $res[$k['vicinity']=urlencode($v['vicinity']); } } } if($res){ $new_res['items']=$res; }else{ $new_res['items']=""; } echo urldecode(json_encode($new_res));}
以上內(nèi)容是小編給大家分享的有關(guān)json_decode亂碼及NULL的問(wèn)題,希望對(duì)大家有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注