Re: [PHP] Problem using fgetcsv()
On Thu, July 6, 2006 11:54 am, Don wrote: I have a CSV file, comma delimited with the data enclosed by double quotes. I am using the fgetcsv() function to read and into an array and update a database. It works great except for the odd record. After investigating, I have ascertained that it is due to a backslash character in the data which fgetcsv() cannot parse properly. I don;t see anyway around this using fgetcsv(). Has anyone written a custom routine for this? Code Snippet --- $vvFile = 'myfile.csv'; $fph = fopen($vvFile,r) if ($fph) { while (($data = fgetcsv($fph,4096,',','')) !== FALSE) {M You *MUST* use: http://php.net/mysql_real_escape_string on each element of the array before cramming it into MySQL. // Insert fields from array '$data' to my MySQL database - will fail on bad data } fclose($fph); } Sample Data -- 123456,135679048754,7154904875,HD INDOOR INSECT KILR 33 OZ 6,EA 654321,246809052607,7154905260,59-2 CACTUS SUCCULENTS \,EA The \ is special to MySQL (and PHP) but not CSV. So your problem is not with CSV -- It's with MySQL input routines. See above. -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Problem using fgetcsv()
I am using the fgetcsv() function to read and into an array and update a database. It works great except for the odd record. After investigating, I have ascertained that it is due to a backslash character in the data which fgetcsv() cannot parse properly. I don;t see anyway around this using fgetcsv(). Has anyone written a custom routine for this? From what I understand, there are multiple CSV formats. The first one I stumbled across specified that the only character escaped inside of a string is , which is printed twice like this. However, after reading some of he user comments in the manual, it seems that MS Excel also accepts \ as an escaped quote and the PHP code follows suit. A quick search in bugs.php.net pulls up this: http://bugs.php.net/bug.php?id=29278 Categorized as a bogus bug, with the standard reply of read the manual and Escaping makes the parser skip over that character. So I guess they're not going to change it. Should be in the documentation, though. You might be better off replacing any \ sequences with \\ before reading from the file (or, if you want to be really fancy, read the file into memory, to the replaces, then use a fopen wrapper to treat the variable like a file so fgetcsv will read from it properly). Hope that helps. -KBear -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php