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条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?