使用 php 清理 JSON

2022-08-31 00:51:54

我总是使用filter_var($var,过滤器,标志);当我从$ _GET,$ _POST等获取数据时,但现在此数据是一个JSON字符串,但我没有找到任何过滤器来清理JSON。有人知道如何实现这个过滤器吗?

菲律宾比索 filter_var(): http://php.net/manual/en/function.filter-var.php

PHP 过滤器常量: http://php.net/manual/en/filter.filters.sanitize.php


答案 1

首先将JSON解析为PHP数组,然后像处理常规请求内容一样过滤数组中的每个值,您可以将JSON键映射到原理图过滤器和标志/选项,例如

$filters = array(
    'email'=>FILTER_VALIDATE_EMAIL, 
    'url'=>FILTER_VALIDATE_URL, 
    'name'=>FILTER_SANITIZE_STRING,
    'address'=>FILTER_SANITIZE_STRING
);
$options = array(
    'email'=>array(
        'flags'=>FILTER_NULL_ON_FAILURE
    ), 
    'url'=>array(
        'flags'=>FILTER_NULL_ON_FAILURE
    ), 
    //... and so on
);
$inputs = json_decode($your_json_data);
$filtered = array();
foreach($inputs as $key=>$value) {
     $filtered[$key] = filter_var($value, $filters[$key], $options[$key]);
}

答案 2

您可以使用filter_var_array

$inputs = filter_var_array( json_decode( $your_json_data, true ), [
   'email'   => [ 'filter' => FILTER_VALIDATE_EMAIL,
                  'flags'  => FILTER_NULL_ON_FAILURE ],
   'url'     => [ 'filter' => FILTER_VALIDATE_URL,
                  'flags'  => FILTER_NULL_ON_FAILURE ],
   'name'    => FILTER_VALIDATE_NAME,
   'address' => FILTER_SANITIZE_STRING
] );

推荐