Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parsing coomma delimited csv files

Status
Not open for further replies.

AllenGarner

Programmer
Joined
Jan 19, 2004
Messages
6
Location
US
I am trying to Upload a csv file then split it up into an an array and build a query to insert it into a mysql table I have succeeded in getting this to work with one exception when I come across a field seperated by commas and enclosed by double quotes if that field also contains double quotes inside of it it throws off my column count I need to be able to consider something like - ,"sometext"some more text"additional text", as one field or value here is what i have so far

Code:
$row = 1; 
$handle = fopen($uploadFile, "r"); 

while ( ($data = fgetcsv($handle, 10000, ",")) != FALSE ) { 
$num = count($data); 
if($row == 1){
$fields = " `id` , ";
for($i=0; $i<$num; $i++){
$fields .= "`" . addslashes(trim($data[$i])) . "` , ";
}
$fields .= "`group` , `user` , "; 
$f = substr($fields, 0, -1);
$f = substr($f, 0, -1);
$row++;
}else{
$values = " '' , "; 
for($i=0; $i<$num; $i++){ 
$values .= "'" . addslashes(trim($data[$i])) . "' , ";
}
$values .= "'personal' , '" . $_SESSION['user'] . "' , ";

$v = substr($values, 0, -1);
$v = substr($v, 0, -1); 
$sql = "INSERT INTO `addressbook` ( $f ) VALUES ( $v )";
mysql_query($sql) or die(print "<center><font size='2' face='verdana' color='#5E6B79'><b>Upload complete some entries may not have been loaded successfully!</b><br><br><a href='addressbook.php' class='light'>Back to Address Book</a></font></center></td></tr></table>");
$values = ''; 
$row++;
} 
}
fclose ($handle);

can anyone help? thanx
 
It looks like this is one instance where fgetcsv doesn't work too well.

Try this, it will get your quoted string into the array correctly:
Code:
$input = file($uploadFile);
for ($i=0;$i<count($input);$i++) {
     $arr = explode(',',trim($input[$i]));
     print_r ($arr); // see what's here then replace this with your code
}

Ken
 
unfortunately sometimes there are commas inside these quotes so as this works for the one situation it throws of the column count if there are any commas I need solution for both
 
The only thing I can think of is to use regular expressions to replace all commas, except those between quotes with some other character that doesn't appear in the string and then doing the explode on that character. Since I'm not too good at regular expressions, someone who is will have to say whether this is feasible or not.

Ken
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top