php判斷是否為json格式的方法
首先要記住json_encode返回的是字符串, 而json_decode返回的是對象
判斷數據不是JSON格式:
function is_not_json($str){
return is_null(json_decode($str));
}
判斷數據是合法的json數據: (PHP版本大于5.3)
function is_json($string) { www.dbjr.com.cn
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
json_last_error()函數返回數據編解碼過程中發(fā)生的錯誤
注意: json編解碼所操作字符串必須是UTF8的
例子
/**
* 解析json串
* @param type $json_str
* @return type
*/
function analyJson($json_str) {
$json_str = str_replace('\\', '', $json_str);
$out_arr = array();
preg_match('/{.*}/', $json_str, $out_arr);
if (!empty($out_arr)) {
$result = json_decode($out_arr[0], TRUE);
} else {
return FALSE;
}
return $result;
}
如果不是json則返回false
PS:關于json操作,這里再為大家推薦幾款比較實用的json在線工具供大家參考使用:
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉換工具:
http://tools.jb51.net/code/jsoncodeformat
在線json壓縮/轉義工具:
http://tools.jb51.net/code/json_yasuo_trans
C語言風格/HTML/CSS/json代碼格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
相關文章
CentOS下PHP7的編譯安裝及MySQL的支持和一些常見問題的解決辦法
這篇文章主要介紹了CentOS下PHP7的編譯安裝及MySQL的支持和一些問題的解決 的相關資料,需要的朋友可以參考下2015-12-12
thinkphp路由規(guī)則使用示例詳解和偽靜態(tài)功能實現(apache重寫)
這篇文章主要介紹了thinkphp路由規(guī)則使用示例詳解和偽靜態(tài)功能實現(apache重寫),需要的朋友可以參考下2014-02-02

