標籤:style blog http color 使用 io ar 資料 2014
/*--------------------------------------------------------------------------------------------------------
@黑眼詩人 <www.chenwei.ws>
--------------------------------------------------------------------------------------------------------*/
php對json字串解碼使用json_decode()函數,第一個參數傳字串,第二個參數若為true,返回array;若為false,返回object。如果返回NULL,說明報錯,輸出json_last_error(),得到的整數值對應錯誤提示。
json_last_error()比較常見的是整數4, 是json字串在json_decode之前已不完整,所以語法錯誤。
那麼一定是用戶端提交的個別字元影響了json的格式,可以使用JS進行過濾,可以解決一般問題,主要過濾斷行符號,空格,html標籤。
/*
* 過濾函數
* @黑眼詩人 <www.chenwei.ws>
*/function htmlEncode(str) { str = str.replace(/\s+/ig, ‘‘); str = str.replace(/&/g, ‘‘); str = str.replace(/</g, ‘‘); str = str.replace(/>/g, ‘‘); str = str.replace(/(?:t| |v|r)*n/g, ‘<br />‘); str = str.replace(/t/g, ‘ ‘); str = str.replace(/x22/g, ‘"‘); str = str.replace(/x27/g, ‘'‘); str = str.replace(/"/g, ""); return str;}
以上情況針對的是,你必須提交json字串資料到服務端處理,只能在用戶端進行過濾。
其它的json_decode($str)返回NULL的一些原因:
1.$str只能UTF-8編碼
2.元素最後不能有逗號(與php的array不同)
3.元素不能使用單引號
4.元素值中間不能有空格和\n,必須替換
如果遇到了此種情況,可以按照以上方式處理一遍。
[PHP]對Json字串解碼返回NULL的一般解決方案