这可能对你有帮助,
标准 JSON 格式不明确支持文件 cmets。 RFC 4627 application/json,这是一种用于存储和传输数据的轻量级格式。如果评论真的很重要,您可以将其包含为另一个数据字段,如 cmets
输入
$ cat test.csv
name,mark,url
ABCD,5,http://www.example.org
BCD,-2,http://www.example.com
CD,4,htt://www.c.com
脚本
<?php
function validate_url($url)
{
return in_array(parse_url($url, PHP_URL_SCHEME),array('http','https')) && filter_var($url, FILTER_VALIDATE_URL);
}
function validate_mark($val)
{
return ($val >= 0 && $val <= 5);
}
function errors($field)
{
$errors = array(
'url' => 'URL should be valid',
'mark' => 'Mark should be between 0 to 5'
);
return ( isset($errors[$field]) ? $errors[$field] : "Unknown");
}
function csv2array_with_validation($filename, $delimiter = ",")
{
$header = $row = $c_row = $output = $val_func = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 0, $delimiter)) !== FALSE)
{
if (empty($header))
{
$header = array_map('strtolower', $row);
foreach ($header as $e)
{
$val_func[$e] = function_exists('validate_' . $e);
}
continue;
}
$c_row = array_combine($header, $row);
$index = 'error_less'; $errors = array();
foreach ($c_row as $e => $v)
{
if ($val_func[$e])
{
if (!call_user_func('validate_' . $e, $v))
{
$index = 'error';
$errors[$e] = errors($e);
}
}
}
/*
If the comment is truly important,
you can include it as another data field like errors,
comment below part if you do not wish to create new field (errors) in
json file
*/
if(!empty($errors))
{
$c_row['errors'] = $errors;
}
$output[$index][] = $c_row;
}
fclose($handle);
}
return $output;
}
$output = csv2array_with_validation('test.csv');
// Write error.json
if (isset($output['error']) && !empty($output['error']))
{
file_put_contents('error.json', json_encode($output['error'], JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK));
}
// Write errorless.json
if (isset($output['error_less']) && !empty($output['error_less']))
{
file_put_contents('error_less.json', json_encode($output['error_less'], JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK));
}
?>
输出
$ php test.php
$ cat error.json
[
{
"name": "BCD",
"mark": -2,
"url": "http:\/\/www.example.com",
"errors": {
"mark": "Mark should be between 0 to 5"
}
},
{
"name": "CD",
"mark": 4,
"url": "htt:\/\/www.c.com",
"errors": {
"url": "URL should be valid"
}
}
]
$ cat error_less.json
[
{
"name": "ABCD",
"mark": 5,
"url": "http:\/\/www.example.org"
}
]