note 34404 added to function.fgetcsv

From: Date: Fri, 25 Jul 2003 20:55:45 +0000
Subject: note 34404 added to function.fgetcsv
Groups: php.notes 
Request: Send a blank email to php-notes+get-52666@lists.php.net to get a copy of this message
If anyone else is taking on the task of converting from FileMaker Pro to MySQL, you might find this useful: Here's a collection of simple functions that take a CSV file, re-formats the data and writes to a file with MySQL INSERTs. ORIGINAL DATA: "1", "foo", "2" "3", "bar", "4" OUTPUT INSERT info mysql_table VALUES('', '1', 'foo', '2'); INSERT info mysql_table VALUES('', '3', 'bar', '4'); For simple data it works alright, but I could not find a way to escape the contents before assembling the INSERT statements - kept getting "bad argument for implode()"... //************************************* // main * //************************************* $file = "path/to/your/file.txt"; $tbl = "your_MySQL_table"; $CSVarray = get_csv($file); $CSVarray = makeINSERTS($CSVarray, "$tbl"); $filetowrite = $_POST["file"]."_sql.txt"; $fp = fopen($filetowrite, "w"); while (list($key, $val) = @each($CSVarray)) { fwrite($fp, $val); } fclose($fp); chmod($filetowrite, 0777); echo "File written Successfully"; } //************************************* // functions * //************************************* // This function courtesy of drudge@phpcoders.net function get_csv($filename, $delim =","){ $row = 0; $dump = array(); $f = fopen ($filename,"r"); $size = filesize($filename)+1; while ($data = fgetcsv($f, $size, $delim)) { $dump[$row] = $data; //echo $data[1]."<br>"; $row++; } fclose ($f); return $dump; } function makeINSERT($text, $table){ $insert = array(); $i = 0; while (list($key, $val) = @each($text)){ // We'll start off the INSERT with '', for an // auto-incremented key. Remove if not needed. $insert[$i] = "INSERT into ".$table." VALUES('','"; $insert[$i] .= implode("','", $val); $insert[$i] .= "');\n"; $i++; } return $insert; } ---- Manual Page -- http://www.php.net/manual/en/function.fgetcsv.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+34404 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+34404&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+34404&report=yes

« previous php.notes (#52666) next »