note 89895 added to function.fgetcsv
| From: | jnolten at gmail dot com | Date: | Fri, 27 Mar 2009 13:52:16 +0000 |
| Subject: | note 89895 added to function.fgetcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-152518@lists.php.net to get a copy of this message | ||
Script to insert the contents of a .csv file ($file in this case) into a MySQL database using more
than one delimiter (so for instance you could use both ; and ,).
Useful because Excel outputs CSV-files with semicolons instead of comma's.
The CSV file must look like this:
[tablename]
[column1],[column2],[column3] etc
[value1row1],[value2row1],[value3row1] etc
[value1row2],[value2row2],[value3row1]
etc
So the value matches with the column.
$data = nl2br(file_get_contents($file));
$data = split("<br />", $data);
$num = count($data);
for ($i = 0; $i <= $num; $i++) {
$data[$i] = split("[,;]", $data[$i]);
$data[$i][0] = str_replace(" ", "", $data[$i][0]);
if ($i == 0) $table = $data[$i][0];
elseif ($i == 1) $column = join(', ', $data[$i]);
else {
$data[$i][0] = ltrim(rtrim($data[$i][0]));
$values = join("', '", $data[$i]);
mysql_query("INSERT INTO ".$table." (".$column.") VALUES
('".$values."')");
if (mysql_error() == '') echo $data[$i][1].' has been added to the database';
//In my CSV files the second column always contains a name
else echo mysql_error();
echo '<br>';
}
}
----
Server IP: 213.249.64.162
Probable Submitter: 94.208.185.227
----
Manual Page -- http://www.php.net/manual/en/function.fgetcsv.php
Edit -- https://master.php.net/note/edit/89895
Del: integrated -- https://master.php.net/note/delete/89895/integrated
Del: useless -- https://master.php.net/note/delete/89895/useless
Del: bad code -- https://master.php.net/note/delete/89895/bad+code
Del: spam -- https://master.php.net/note/delete/89895/spam
Del: non-english -- https://master.php.net/note/delete/89895/non-english
Del: in docs -- https://master.php.net/note/delete/89895/in+docs
Del: other reasons-- https://master.php.net/note/delete/89895
Reject -- https://master.php.net/note/reject/89895
Search -- https://master.php.net/manage/user-notes.php