使用奇数封装的// CSV文件// PHP

时间:2010-04-10 08:00:24

标签: php csv

我有一个我正在使用的CSV文件,所有字段都以逗号分隔。但是一些字段本身包含逗号。在原始CSV文件中,包含逗号的字段用引号封装,如此处所示;

"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);
?>

问题是我得到的字段用逗号分成两个字段,这会混淆我应该拥有的列数。

有什么方法可以在引号内搜索逗号并转换它们,或者用其他方式来处理它?<​​/ p>

2 个答案:

答案 0 :(得分:6)

您可以使用“enclosure”参数。请参阅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
)

答案 1 :(得分:0)

您可以搜索每一行是否包含逗号并采取相应的行动:

 foreach($line AS $key => $value){
    if (strpos($value, ',') !== false)
    {
       // there is a comma in this value
    }
    else
    {
       // there is no comma
    }
}