1

我正在下载远程文本文件并将其导入本地 mysql 数据库。

格式最近已更改为在其中一列内有一个逗号,并导致导入失败,并出现错误“第 1 行 CSV 输入中的字段计数无效”。数据现在看起来像:

"bonita","FL","212025920","2012929","Hooker,Bill"

如何更新此代码片段以允许引号内有逗号?

foreach(explode($lineseparator,$csvcontent) as $line) {

    $lines++;

    $line = trim($line," \t");

    $line = str_replace("\r","",$line);

    /************************************
    This line escapes the special character. remove it if entries are already escaped in the csv file
    ************************************/
    $line = str_replace("'","\'",$line);
    /*************************************/

    $linearray = explode($fieldseparator,$line);

    $linemysql = implode("','",$linearray);

    $linemysql = str_replace("\"","",$linemysql);###code added

        $query = "insert ignore into $databasetable values('$linemysql');";
4

3 回答 3

3

LOAD DATA LOCAL INFILEwith FIELDS TERMINATED BY ',' ENCLOSED BY '"'options 应该直接读取文件。LOAD DATA INFILE也比标准INSERT语句快。

http://dev.mysql.com/doc/refman/5.1/en/load-data.html

这很接近,但我不认为 TRIM() 正在删除标签:

LOAD DATA LOCAL INFILE '/my/local/file/path.csv' IGNORE INTO TABLE mytable FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' (@a, @b, @c, @d, @e) SET col1=TRIM(@a), col2=TRIM(@b), col3=TRIM(@c), col4=TRIM(@d) col5=TRIM(@e)

于 2012-11-04T14:18:20.337 回答
2

将您的函数重写为:

     foreach(explode($lineseparator,$csvcontent) as $line) {

        $lines++;
        $line = trim($line," \t");
        $line = str_replace("\r","",$line);

        $lineArray = str_getcsv($line, ",", '"');
        $linemysql = implode("','",$lineArray);
         $query = "insert ignore into $databasetable values('$linemysql');";
        //.. Handle  the rest

     }

php getcsv 函数负责处理分隔符并跟踪附件 - 为您省去这些麻烦。

以下片段:

   $line = '"bonita","FL","212025920","2012929","Hooker,Bill"';
   $array = str_getcsv($line, ",", '"');
   print_r($array);

输出:

   Array ( [0] => bonita [1] => FL [2] => 212025920 [3] => 2012929 [4] => Hooker,Bill )
于 2012-11-04T14:31:06.107 回答
0

样品表:

CREATE TABLE `table1` (
    `id` VARCHAR(50) NULL DEFAULT NULL,
    `a1` VARCHAR(50) NULL DEFAULT NULL,
    `b1` VARCHAR(50) NULL DEFAULT NULL,
    `c1` VARCHAR(50) NULL DEFAULT NULL,
    `d1` VARCHAR(50) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoD1B;

进口查询:

load data local infile 'd:/import.csv' into table table1 fields terminated by ','
enclosed by '"'
lines terminated by '\r\n'
(id, a1, b1, c1, d1)

导入.csv

"bonita1","FL1","212025920","2012929","Hooker,Bill"
"bonita2","FL2","212025920","2012929","Hooker,Bill"
"bonita3","FL3","212025920","2012929","Hooker,Bill"
于 2012-11-04T14:19:17.720 回答