doudou0111 2014-04-25 00:28 采纳率: 0%
浏览 26
已采纳

如何使用php删除CSV文件中的额外逗号

I'm writting a PHP script to import a CSV file to MySQL table.

My problem is that fields are separated by commas, but some fields came within an extra comma, or double quotes (I alread found the solution for double quotes), But not for extra commas. This is an example:

SORT_COLUMN,SORT_ALPHA,GUEST_NAME,PROFILE_ID,FULL_ADDRESS,IS_TOTAL_YN
0,DIAZ REBOLLO ANGELICA,Diaz Rebollo Angelica,824990,"Blvd. Manuel Avila Camacho 36, piso 10   Lomas de Chapul DF 11000"

As you can see in the FULL ADDRESS field:

"Blvd. Manuel Avila Camacho 36, piso 10   Lomas de Chapul DF 11000"

Comes with " and a comma before 36,

This is part of the PHP CODE:

$lineseparator = "
";
foreach(explode($lineseparator,$csvcontent) as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("","",$line);

    // Here I remove double quotes in the csv file
    $line =  str_replace(""",'',$line);
    $linearray = explode($fieldseparator,$line);
    $linemysql = implode("','",$linearray);
    $query = "insert into $databasetable values('$linemysql');";
    $queries .= $query . "
";
    @mysql_query($query);
}
  • 写回答

2条回答 默认 最新

  • dtxs9017 2014-04-25 00:54
    关注

    fgetcsv—which is a part of the standard PHP library—is your friend.

    Well, most of the time. Note, of course, the $escape parameter, which is weird, useless, and broken. You need to pass 0 (note: the literal integer zero, not any of the other zero-ish things in PHP) to disable it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?