dongpeihui1051 2012-09-24 20:44
浏览 66
已采纳

使用新行作为分隔符解析CSV

I have the following in a CSV file exported from Excel

Lol,Man,11
Hello,World,11
My,Name,12
Is,Epic,11

How would I parse this using PHP to an array?

Currently I am using

$line = file_get_contents("Day1.CSV");

$parsed = str_getcsv(
    $line, # Input line
    ',',   # Delimiter
    '"',   # Enclosure
    '//'   # Escape char
);

But that's not working.

  • 写回答

2条回答 默认 最新

  • douou2026 2012-09-24 20:56
    关注

    You can use fgetcsv (example from the manual page)

    if (($handle = fopen("Day1.CSV", "r")) !== FALSE) 
    {
        while (($data = fgetcsv($handle, 1000, ",", "//")) !== FALSE) 
        {
            // do something with the data here
            echo $data[0] . " - ". $data[1] . " - ". $data[2] . "</br>" ;
        }
        fclose($handle);
    }
    

    Alternatively in your implementation, you can do this:

    $contents = file_get_contents("Day1.CSV");
    
    $data = str_getcsv("
    ");
    
    foreach ($data as $row)
    {
        $output = str_getcsv($row, ',', '"', '//');
    
        // do something with the data here
        echo $output[0] . " - " $output[1] . " - " $output[2] . "
    ";
    }
    

    HTH

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

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启