note 35533 deleted from function.fgetcsv by aidan
| From: | aidan@php.net | Date: | Thu, 01 Jul 2004 01:02:14 +0000 |
| Subject: | note 35533 deleted from function.fgetcsv by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72211@lists.php.net to get a copy of this message | ||
Note Submitter: fred weil @ infoiq co uk
----
Fix to brian at brianvoss dot com contribution that adds slashes to characters that need to be
quoted in database queries.
<HTML>
<HEAD></HEAD>
<BODY>
<?php
/* 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 *
//*************************************
echo ("Start<BR>");
$file = "bre_rota.csv";
$tbl = "rota";
$CSVarray = get_csv($file);
$CSVarray = insertADDSLASHES($CSVarray);
$CSVarray = makeINSERT($CSVarray, "$tbl");
$filetowrite = $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 insertADDSLASHES($text){
$addsl = array();
while (list($key) = each($text)){
while (list($key2,$val) = each($text[$key])){
// echo ("$val". " ". $key." ". $key2. "<BR>");
$addsl[$key][$key2] = addslashes($val);
}
}
return $addsl;
}
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;
}
?>
</BODY>
<HTML>