2014-02-07 39 views
1

我要添加下面的驗證,同時上傳CSV文件 如有CSV字符串是空白的,它應該拋出一個錯誤 IM使用驗證了

<? 
test.csv contains 
1,2,3,4 
2,,5,6 
$csvFile = 'test.csv'; 
$csv = readCSV($csvFile); 


function readCSV($csvFile) 
    { 
    $file_handle = fopen($csvFile, 'r'); 
    while (!feof($file_handle)) { 

     $line_of_text[] = fgetcsv($file_handle, 1024); 
    } 

    fclose($file_handle); 
    return $line_of_text; 
} 
?> 

回答

2
$csvFile = 'test.csv'; 
$csv = readCSV($csvFile); 

function readCSV($csvFile) { 
    $file_handle = fopen($csvFile, 'r'); 
    while (!feof($file_handle)) { 
     $current_line = fgetcsv($file_handle, 1024); 
     if(in_array('', $current_line) { 
      throw new Exception('Some data is missing'); 
     } 
     else { 
      $line_of_text[] = $currentLine; 
     } 
    } 

    fclose($file_handle); 
    return $line_of_text; 
} 
1

我認爲你將CSV到陣列中的CSV空值要求驗證每個csv行,以確保該行的數組中沒有值爲空。如果這是正確的,你可以這樣做:

while (!feof($file_handle)) { 

    $currentLine = fgetcsv($file_handle, 1024); 
    $valid = true; 
    for each ($currentLine as $currentValue) { 
     //validation 
     if (empty($currentValue)) { 
      // validation 
      $valid = false; 
     } 
    } 
    if ($valid) { 
     $line_of_text[] = $currentLine; 
    } 
}