I am building a tool that will accept a CSV or tab-delimited file, which will then be parsed and the data databased.
The uploaded file can be CSV or tab-delimited.
I came up with a workable solution (below) for detecting what format the file might be in and would like to know if there is a better way to solve this and/or how any of you out there have solved the same problem.
Thanks
<?php
$csv_comma='Fruit,Color
Apple,"Red,Green"
Tomato,"Red,Green"
Banana,Yellow
Tangerine,Orange
';
$csv_semi_colon='Fruit;Color
Apple;"Red,Green"
Tomato;"Red,Green"
Banana;Yellow
Tangerine;Orange
';
$tab_delimited='Fruit Color
Apple Red,Green
Tomato Red,Green
Banana Yellow
Tangerine Orange';
$fileArr = array($csv_comma,$csv_semi_colon,$tab_delimited);
foreach($fileArr as $file){
if(preg_match('/^(.+),(.+)/',trim($file))){
echo "CSV with comma separator";
}
if(preg_match('/^(.+);(.+)/',trim($file))){
echo "CSV with semi colon separator";
}
if(preg_match('/^(.+)\t(.+)/',trim($file))){
echo "Tab delimited";
}
}