note 103891 modified in function.fgetcsv by danbrown
| From: | danbrown@php.net | Date: | Wed, 11 May 2011 15:47:05 +0000 |
| Subject: | note 103891 modified in function.fgetcsv by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-179627@lists.php.net to get a copy of this message | ||
Here is a function that accepts the path to a CSV file, and inserts all records to the given MySQL
table, paying attention to the column names:
<?php
function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) {
if (($handle = fopen("$source_file", "r")) !== FALSE) {
$columns = fgetcsv($handle, $max_line_length, ",");
foreach ($columns as &$column) {
$column = str_replace(".","",$column);
}
$insert_query_prefix = "INSERT INTO $target_table
(".join(",",$columns).")\nVALUES";
while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
while (count($data)<count($columns))
array_push($data, NULL);
$query = "$insert_query_prefix
(".join(",",quote_all_array($data)).");";
mysql_query($query);
}
fclose($handle);
}
}
?>
This assumes that the columns in the table have exactly the same name as the columns in the CSV
file, except that the dots (".") are removed. This is because MySQL column names cannot
contain dots.
--was--
Here is a function that accepts the path to a CSV file, and inserts all records to the given MySQL
table, paying attention to the column names:
<?php
function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) {
if (($handle = fopen("$source_file", "r")) !== FALSE) {
$columns = fgetcsv($handle, $max_line_length, ",");
foreach ($columns as &$column) {
$column = str_replace(".","",$column);
}
$insert_query_prefix = "INSERT INTO $target_table
(".join(",",$columns).")\nVALUES";
while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
while (count($data)<count($columns))
array_push($data, NULL);
$query = "$insert_query_prefix
(".join(",",quote_all_array($data)).");";
mysql_query($query);
}
fclose($handle);
}
}
?>
http://php.net/manual/en/function.fgetcsv.php