paalg/csv

一个处理CSV文件的库

v0.1.0 2023-09-11 11:43 UTC

This package is auto-updated.

Last update: 2024-09-12 10:52:49 UTC


README

此库用于解析并迭代CSV文件中的行。

版本

  • v0.1 第一个发布的版本

用法

// Load standard CSV file with headers and "," as field separator
$csv = new Csv('import.csv');
$data = $csv->getData();
print_r($data);
print_r($csv->getHeaders());

上述代码的输出可能如下

Array
(
    [0] => Array
        (
            [Year] => 1997
            [Make] => Ford
            [Model] => E350
            [Description] => ac, abs, moon
            [Price] => 3000.00
        )

    [1] => Array
        (
            [Year] => 1999
            [Make] => Chevy
            [Model] => Venture "Extended Edition"
            [Description] => 
            [Price] => 4900.00
        )
)
Array
(
    [0] => Year
    [1] => Make
    [2] => Model
    [3] => Description
    [4] => Price
)

如果您需要迭代CSV文件,可以这样做

$csv = new Csv('data.csv');
foreach ($csv as $row) {    
    print_r($row);
    foreach ($row as $fieldName => $value) {
        // do things with the fields in current row
    }
}

上述脚本的每次迭代将输出类似以下内容

Array
(
    [Year] => 1999
    [Make] => Chevy
    [Model] => Venture "Extended Edition"
    [Description] =>
    [Price] => 4900.00
)

单元测试

该库已经通过单元测试(phpunit)进行了彻底测试。您可以使用命令 composer test 运行测试。