在PHP中导入CSV验证

时间:2018-05-21 12:02:24

标签: php csv fgetcsv

我正在尝试上传/导入CSV到SQL服务器,并进行一些基本验证,例如 CSV标头应包含'SecurityID'和'SecurityID'值不能为NULL并且具有NUMERIC值。我有一些问题验证标题部分和卡住。以下是 functions.php 的代码。为清楚起见,我删除了数据库插入/更新代码,因为我没有那么远。

    if(isset($_POST["Import"])){

            $filetempname=$_FILES['file']['tmp_name'];
            $filename=$_FILES['file']['name'];
            $filetype = $_FILES['file']['type'];

            $csv_mimetypes = array(
                            'text/csv',
                            'text/plain',
                            'application/csv',
                            'text/comma-separated-values',
                            'application/excel',
                            'application/vnd.ms-excel',
                            'application/vnd.msexcel',
                            'text/anytext',
                            'application/octet-stream',
                            'application/txt',
                        );
            $expectedHeaders = array(
                'SecurityID'
            );

            $requiredFields = array(
                'SecurityID'
            );

            $firstLine = true;

            if (in_array($_FILES['file']['type'],$csv_mimetypes)) 
            {
                if($_FILES["file"]["size"] > 0)
                {
                $file = fopen($filetempname, "r");
                #echo $file;

                while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
                {   
                    foreach($getData as $row)
                    {
                        if($firstLine)
                        {
var_dump($expectedHeaders);
                            //Set the headers:
                            $firstLine = false;
var_dump($getData);
                            $headers = array_flip($getData);

                            // Validate the headers:
                            if($headers !== $expectedHeaders)
                            {
                                echo "Invalid headers. Aborting import.";
                            }
                            Continue;
                        }

                        foreach($requiredFields as $requiredKey)
                        {
                            $value = $row[$headers[$requiredKey]];
                            // '0' will also match as empty(), although it is a valid value:
                            if(empty($value) && $value != '0' && is_numeric($value))
                            {
                                echo "Row {$requiredKey} may not be empty or has to be numeric. Aborting import.";
                            }
                        }
                        fclose($file);  
                        }
                    }
                }
            }
            else
            { 
                echo "<script type=\"text/javascript\">
                alert(\"Invalid File:Please Upload CSV File.\");
                window.location = \"indexd.php\"
                </script>";
            }
        }

尝试上传/验证CSV我遇到以下错误。 IIS网络服务器日志没有给我任何东西..:

Invalid headers. Aborting import.

的var_dump($的getData);给我下面的信息:

array(15) { 
[0]=> string(14) "DataProviderID" 
[1]=> string(8) "FamilyID" 
[2]=> string(10) "FamilyName" 
[3]=> string(10) "SecurityID" 
[4]=> string(4) "Name" 
[5]=> string(10) "PrimaryRic" 
[6]=> string(13) "Administrator" 
[7]=> string(16) "IsAdminEULocated" 
[8]=> string(21) "IsAdminOnEsmaRegister" 
[9]=> string(25) "IsBenchmarkOnEsmaRegister" 
[10]=> string(26) "IsBenchmarkOnAdminRegister" 
[11]=> string(23) "HasEUListedFundTracking" 
[12]=> string(25) "HasEUListedFutureOrOption" 
[13]=> string(20) "IsAdminPre2016Active" 
[14]=> string(24) "IsBenchmarkPre2018Active" 
}

的var_dump($ expectedHeaders);给我下面的信息:

array(1) { 
[0]=> string(10) "SecurityID" 
}

我的测试CSV文件如下:

DataProviderID,FamilyID,FamilyName,SecurityID,Name,PrimaryRic,Administrator,IsAdminEULocated,IsAdminOnEsmaRegister,IsBenchmarkOnEsmaRegister,IsBenchmarkOnAdminRegister,HasEUListedFundTracking,HasEUListedFutureOrOption,IsAdminPre2016Active,IsBenchmarkPre2018Active
2,MSCI,MSCI Main Indices - Americas,17912,NORTH AMERICA IMI-664176,.dMINA000I0PUS,MSCI Limited,1,1,0,99,99,99,99,1

1 个答案:

答案 0 :(得分:1)

我添加了一些var_dump,以便您可以看到代码的功能。当某些东西不能按预期工作时总是验证你的变量(“它是否保持我期望它的值?”):

// [...]
$expectedHeaders = array(
    'SecurityID'
);

var_dump($expectedHeaders);
// Will print array(
//    0 => (string) 'SecurityID'
// )

// [...] while foreach etc

//Set the headers:
$firstLine = false;

var_dump($getData);
// Will print array(
//    0 => (string) 'DataProviderID'
//    1 => (string) 'FamilyID'
//    2 => (string) 'FamilyName'
//    3 => (string) 'SecurityID'
//    etc
// );

$headers = array_flip($getData);

var_dump($headers);
// Will print array(
//    (string) 'DataProviderID' => 0
//    (string) 'FamilyID'       => 1
//    (string) 'FamilyName'     => 2
//    (string) 'SecurityID'     => 3
//    etc
// )

// Validate the headers:
if($headers !== $expectedHeaders) 
{
    // Will always get into this if, because as you can see
    // from the var_dumps, $expectedHeaders will never be 
    // equal to $headers - nor equal to $getData
    echo "Invalid headers. Aborting import.";
}

以下if语句的可能解决方案。 array_intersect会将$getData中的值与$expectedHeaders中的值相同。如果$getData包含更多标题,则会array_intersect删除这些标题,从而导致相同的计数(假设顺序无关紧要)。如果$getData缺少标题,则该交集的计数将小于$expectedHeaders的计数。

if (
    count(array_intersect($getData, $expectedHeaders)) 
    != count($expectedHeaders)
) {
    // Wrong CSV format error
}