如果缺少某些数据,我会检查csv文件,
数组的标头包含需要匹配的字符串。
首先我需要检查第一个数组是否包含日期,时间,L1,L2,L3
从第二个数组开始,它应该始终检查日期和时间格式。
以下是我试过的代码
$file_handle = fopen($csvFile, 'r');
$current_line="";
echo "<pre>";
$i=0;
while (!feof($file_handle) ) {
$current_line = fgetcsv($file_handle, 1024);
print_r($current_line);
if(@in_array('', $current_line) )
{
throw new Exception('Some data is missing');
}
else {
$line_of_text[] = $current_line;
//print_r($line_of_text);
}
$i++;
}
fclose($file_handle);
打印$ current_line给我这个
Array
(
[0] => Date
[1] => Time
[2] => L1
[3] => L2
[4] => L3
)
Array
(
[0] => 10/31/2013
[1] => 13:53:35
[2] => 39.8
[3] => 36.2
[4] => 39.6
)
Array
(
[0] => 10/31/2013
[1] => 13:53:40
[2] => 39.8
[3] => 36.6
[4] => 39.7
)
答案 0 :(得分:1)
试试这个:
$file_handle = fopen($csvFile, 'r');
$a_cols_sample = array('Date', 'time', 'L1', 'L2', 'L3');
$a_cols = fgetcsv($file_handle, 1024);
if (!($a_cols && count($a_cols) == 5 && $a_cols === $a_cols_sample)) return;
$result = array();
while (($a_vals = fgetcsv($file_handle, 1024)) !== false) {
if (count($a_vals) != 5) continue;
list($date, $time, , , ) = $a_vals;
if (date_create_from_format('d/m/Y', $date) === false) continue;
if (date_create_from_format('h:i:s', $time) === false) continue;
$result[] = $a_vals;
}
print_r($result);
fclose($file_handle);