如何使用fgetcsv()解析csv文件中以分号分隔的文本行


How to parse semicolon-delimited lines of text in a csv file with fgetcsv()

我正在尝试读取一个CSV文件,并将其转换为这样的数组。

$h = fopen("onderdelen-test.csv", "r");
echo '$parts = array(';
if($h) {
    while (($data = fgetcsv($h, 1000)) !== FALSE) {
        foreach ($data as $num) {
            $part = explode(';', "$num");
            echo "array('partid' => '$part[0]', ";
            echo "'descr' => '$part[1]'), ";
        }
    }
    fclose($h);
}
echo ')';

csv看起来像这个

123456 ; partdescription
234567 ; partdescription, anotherdescription
345678 ; part, description and some other description

问题是它也会在逗号上爆炸,而不仅仅是在分号上。我试着在描述周围添加引号,但确实在描述周围加了一些奇怪的问号,我无法摆脱。

编辑1:如果我在fgetcsv函数中使用分号作为分隔符,那么我无法按键检索值,它只是在每次找到分号时启动另一个循环。

保持简单,因为你所要做的就是在进行更大的事情之前看看这个输入产生了什么

123456 ; partdescription
234567 ; partdescription, anotherdescription
345678 ; part, description and some other description

这个代码,注意我已经将第三个参数添加到fgetcsv

<?php
$h = fopen("onderdelen-test.csv", "r");
if($h) {
    while (($data = fgetcsv($h, 1000, ';')) !== FALSE) {
        print_r($data);
        echo "partid = " . trim($data[0]) . "'n";
        echo "descr  = " . trim($data[1]) . "'n";
    }
    fclose($h);
}

产生此输出

Array
(
    [0] => 123456
    [1] =>  partdescription
)
partid = 123456
descr =  partdescription
Array
(
    [0] => 234567
    [1] =>  partdescription, anotherdescription
)
partid = 234567
descr =  partdescription, anotherdescription
Array
(
    [0] => 345678
    [1] =>  part, description and some other description
)
partid = 345678
descr =  part, description and some other description

解析csv文件的简单片段:

    $i=0; $keys=array(); $output=array();
    $handle=fopen("onderdelen-test.csv", "r");
    if ($handle){
        while(($line = fgetcsv($handle,0,';')) !== false) {
            $i++;
            if ($i==1) {
                $keys=$line;
            } elseif ($i>1){
                $attr=array();
                foreach($line as $k=>$v){
                    $attr[trim($keys[$k])]=$v;
                }
                $output[]=$attr;
            }
        }
        fclose($handle);
    }
    //$output here is your data array

在这里,您将从csv文件中获得关联数组,其中键来自文件的第一行。

    id ; description
123456 ; partdescription
234567 ; partdescription, anotherdescription
345678 ; part, description and some other description

结果数组:

Array
(
    [0] => Array
        (
            [id] => 123456 
            [description] =>  partdescription
        )
    [1] => Array
        (
            [id] => 234567 
            [description] =>  partdescription, anotherdescription
        )
    [2] => Array
        (
            [id] => 345678 
            [description] =>  part, description and some other description
        )
)

你的echo真的有点不对。