如何使用 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 函数中使用分号作为分隔符,那么我无法按键检索值,每次找到分号时它都会启动另一个循环。

解析 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确实有点不对。

保持简单,因为您要做的就是在继续进行更大的事情之前查看此输入产生的结果

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