I have a basic import tool that we are using to upload into our database using PHP. Here is a sample script. My question is how can I validate the headers before import? Basically check against a value to make sure the right file is getting imported.I looked everywhere online, but can't seem to find the answer My headers are
SKU, Price, Active
LOAD DATA LOW_PRIORITY LOCAL INFILE '$file' INTO TABLE
sample
.your_temp_table
FIELDS TERMINATED BY ' ' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES //Continue to run rest of script
My question is how to validate the headers before the script is ran? I'm using
$file = $_GET['file']; $file = urldecode ($file); //getting file on upload
I tried to upload a CSV and got an "Invalid Header" error. What should I do next? This error is usually caused by formatting or white space changes in the header of the CSV file you're attempting to upload. You can fix this very quickly by copying the entire header row from our Sample CSV file.
A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. Initially, the CSV file is converted to a data frame and then a header is added to the data frame. The contents of the data frame are again stored back into the CSV file.
I.e., if you want to validate data from a CSV file, you have to first construct a CSV reader using the standard Python csv module, specifying the appropriate dialect, and then pass the CSV reader as the source of data to either the CSVValidator. validate or the CSVValidator. ivalidate method.
I think you will need to read the first line of the $file
and compare it to a set list of headers:
$requiredHeaders = array('SKU', 'Price', 'Active'); //headers we expect
$f = fopen($file, 'r');
$firstLine = fgets($f); //get first line of csv file
fclose($f); // close file
$foundHeaders = str_getcsv(trim($firstLine), ',', '"'); //parse to array
if ($foundHeaders !== $requiredHeaders) {
echo 'Headers do not match: '.implode(', ', $foundHeaders);
die();
}
//run import script…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With