Home  >  Article  >  Backend Development  >  A case of php detecting whether the json format is correct

A case of php detecting whether the json format is correct

黄舟
黄舟Original
2017-09-21 09:09:401527browse

This article will share with you the implementation code of PHP to determine whether the json format is correct. The code is simple and easy to understand, very good, and has reference value. Friends who need it can refer to it

No more nonsense, just give it to Everyone has posted the code. The specific code is as follows:


<?php
$GLOBALS[&#39;count&#39;] = 0;
//校验data或者content的json格式是否有错误
function data($value) {
  if (isset($value[&#39;data&#39;])) {
    $value[&#39;data&#39;] = json_decode($value[&#39;data&#39;], true);
  } else if (isset($value[&#39;content&#39;])) {
    $value[&#39;content&#39;] = json_decode($value[&#39;content&#39;], true);
  } else {
    die(&#39;必须要有content或者data字段&#39;);
  }
  $error = json_last_error();
  if (!empty($error)) {
    echo "<pre class="brush:php;toolbar:false">";
    print_r($value);
    echo "
"; } return $value; } //校验静态资源是否存在; function my_filter($value) { $needle = ['.jpg', '.jpeg', '.png', '.avi', '.mp4', '.wav', '.gif', '.mp3']; $root = 'D:/phpStudy/WWW/levelData/'; foreach ($needle as $k => $v) { $aa = strpos($value, $v); if ($aa) { $file = $root . $value; if (!file_exists($file)) { $GLOBALS['count']++; return $value; } } } } //获取多维数组里面某一列的下标,并重新组成一维数组 function searchMultiArray(array $array, $search, $mode = 'key') { $res = array(); foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key => $value) { if ($search === ${${"mode"}}) { if ($mode == 'key') { $res[] = $value; } else { $res[] = $key; } } } return $res; } function my_filter_answer($value) { $needle = [',', '、', ' ', '.', ',,', ',,']; foreach ($needle as $k => $v) { $aa = strpos($value, $v); if ($aa) { return 1; } } } //将汉字,特殊字符原样变成json数据 function ch_json_encode($data) { $ret = ch_urlencode($data); $ret = json_encode($ret); return '\'' . addslashes(urldecode($ret)) . '\''; } //汉字,特殊字符变可读懂的字符串主程序 function ch_urlencode($data) { if (is_array($data) || is_object($data)) { foreach ($data as $k => $v) { if (is_scalar($v)) { if (is_array($data)) { $data[$k] = urlencode($v); } else if (is_object($data)) { $data->$k = urlencode($v); } } else if (is_array($data)) { $data[$k] = ch_urlencode($v); // 递归调用该函数 } else if (is_object($data)) { $data->$k = ch_urlencode($v); } } } return $data; }

Summary

The above is the detailed content of A case of php detecting whether the json format is correct. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn