使用具有奇怪封装的CSV文件//PHP [英] Working with a CSV file with odd encapsulation // PHP

查看:91
本文介绍了使用具有奇怪封装的CSV文件//PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在使用的CSV文件,并且所有字段均以逗号分隔.但是某些字段本身包含逗号.在原始CSV文件中,包含逗号的字段用引号引起来,如此处所示;

I have a CSV file that I'm working with, and all the fields are comma separated. But some of the fields themselves, contain commas. In the raw CSV file, the fields that contain commas, are encapsulated with quotes, as seen here;

"Doctor Such and Such, Medical Center","555 Scruff McGruff, Suite 103, Chicago IL 60652",(555) 555-5555,,,,something else

我正在使用的代码如下

<?PHP
    $file_handle = fopen("file.csv", "r");
    $i=0;
    while (!feof($file_handle) ) {
        $line = fgetcsv($file_handle, 1024);
        $c=0;
        foreach($line AS $key=>$value){
            if($i != 0){
                if($c == 0){
                    echo "[ROW $i][COL $c] - $value"; //First field in row, show row #
                }else{
                    echo "[COL $c] - $value"; // Remaining fields in row
                }
            }
            $c++;
        }
        echo "<br>"; // Line Break to next line
        $i++;
    }
    fclose($file_handle);
?>

问题是我将逗号分隔的字段分为两个字段,这弄乱了我应该具有的列数.

The problem is I'm getting the fields with the commas split into two fields, which messes up the number of columns I'm supposed to have.

我有什么办法可以搜索引号内的逗号并将其转换,或者另一种处理方式?

Is there any way I could search for commas within quotes and convert them, or another way to deal with this?

推荐答案

您可以使用附件"参数.请参见fgetcsv 文档.

You can use the "enclosure" parameter. See the fgetcsv documentation.

$handle = fopen("file", "r");
if ($handle ) {
    while (($line = fgetcsv($handle, 2048, ",", '"')) !== FALSE) {
      print_r( $line)."\n";
    }
    fclose($handle);
}

输出:

$ cat file
"Doctor Such and Such, Medical Center","555 Scruff McGruff, Suite 103, Chicago IL 60652",(555) 555-5555,,,,something else

$ php test.php
Array
(
    [0] => Doctor Such and Such, Medical Center
    [1] => 555 Scruff McGruff, Suite 103, Chicago IL 60652
    [2] => (555) 555-5555
    [3] =>
    [4] =>
    [5] =>
    [6] => something else
)

这篇关于使用具有奇怪封装的CSV文件//PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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