douyan1244 2013-12-29 11:29
浏览 159
已采纳

当列值本身包含逗号时,以逗号分隔的CSV文件进行爆炸

I am reading a comma deliminated CSV file line by line and then separate each column value using PHP explode function. The problem is that there are some columns which itself have comma (,) values in it so they are also exploded.

A row of data:

03,1392,06,1000,1,"1000,36,21,68",4,AF,TJ,AF,44071000

Here "1000,36,21,68" must be considered as a single value but PHP explode also breaks it. I know this is how explode works but is there any alternate function which can be used in this case. Also i would need to remove the double quotes (") from both sides from this value.

  • 写回答

1条回答 默认 最新

  • dongxinpa3101 2013-12-29 11:31
    关注

    Don't try using explode and parsing it yourself:

    use PHP's built-in str_getcsv() function

    or use fgetcsv() to read and parse each line directly from file

    EDIT

    If you're feeling really adventurous, you can use SPL to read and parse the file

    $file = new SplFileObject("data.csv");
    while (!$file->eof()) {
        var_dump($file->fgetcsv());
    }
    

    or

    $file = new SplFileObject("data.csv");
    $file->setFlags(SplFileObject::READ_CSV);
    foreach ($file as $fields) {
        var_dump($fields);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记