php判断数据是不是json的方法:1、创建一个PHP示例文件;2、通过“function analyJson($json_str) {...}”方法判断数据是不是json即可。

本文操作环境:windows7系统、PHP7.4版、DELL G3电脑
php判断是否为json格式的方法
http://www.poluoluo.com/jzxy/201403/265005.html
立即学习“PHP免费学习笔记(深入)”;
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) {
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}
json_last_error()函数返回数据编解码过程中发生的错误
注意: 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
推荐学习:《PHP视频教程》
                        
                        PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号