如何解析CSV与PHP,但忽略逗号和双引号的字符串 [英] How can I parse a CSV with php but ignore the commas and double quotes in the strings

查看:276
本文介绍了如何解析CSV与PHP,但忽略逗号和双引号的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将csv文件解析为数组。不幸的是,其中一个列包含逗号和引号(下面的示例)。任何建议如何避免将列分成多个列?

I am trying to parse a csv file into an array. Unfortunately one of the columns contains commas and quotes (Example below). Any suggestions how I can avoid breaking up the column in to multiple columns?

我尝试更改fgetcsv函数中的分隔符,但是没有工作,所以我试过使用

I have tried changing the deliminator in the fgetcsv function but that didn't work so I tried using str_replace to escape all the commas but that broke the script.

CSV格式示例

title,->link,->description,->id
Achillea,->http://www.example.com,->another,short example "Of the product",->346346
Seeds,->http://www.example.com,->"please see description for more info, thanks",->34643
Ageratum,->http://www.example.com,->this is, a brief description, of the product.,->213421

    // Open the CSV
    if (($handle = fopen($fileUrl, "r")) !==FALSE) {

        // Set the parent array key to 0
        $key = 0;

        // While there is data available loop through unlimited times (0) using separator (,)
        while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {

           // Count the total keys in each row
           $c = count($data);

           //Populate the array
           for ($x = 0; $x < $c; $x++) {
           $arrCSV[$key][$x] = $data[$x];
           }
           $key++;
        } // end while

        // Close the CSV file
        fclose($handle);
    }


推荐答案

也许您应该考虑使用PHP的 file() - 函数将CSV文件读入数组。

Maybe you should think about using PHP's file()-function which reads you CSV-file into an array.

根据您的分隔符,您可以使用

Depending on your delimiter you could use explode() then to split the lines into cells.

这里有一个例子:

$csv_file("test_file.csv");

foreach($csv_file as $line){
  $cell = explode(",->", $line);  // ==> if ",->" is your csv-delimiter!

  $title[] = $cell[0];
  $link[] = $cell[1];
  $description = $cell[2];
  $id[] = $cell[3];
}

这篇关于如何解析CSV与PHP,但忽略逗号和双引号的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆