mmerian / csv

一个用于轻松读取和写入CSV文件的库

1.0.10 2016-03-15 08:50 UTC

This package is auto-updated.

Last update: 2024-09-25 06:47:05 UTC


README

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

此库旨在帮助您读取和写入csv文件。

用法

读取CSV文件

假设你有一个看起来像这样的CSV文件

first_name;last_name;gender;birthdate
John;Smith;M;1972-05-12
Susan;Chatman;F;1972-05-12

实例化读取器非常简单

use Csv\Reader;

$reader = new Reader($file, array(
    'hasHeader' => true,
    'inputEncoding' => 'ISO-8859-15',
    'outputEncoding' => 'UTF-8',
    'delimiter' => ';'
));

foreach ($reader as $line) {
    /*
     * $line is an array.
     * If the CSV file has an header,
     * the array keys are the header fields
     */
    echo $line['first_name'];
}

// Or

while ($line = $reader->fetch()) {
    // Process line
}

在这个例子中,$file 可以是现有文件的路径,或指向已打开文件的指针。可用选项包括

  • 'hasHeader':一个布尔值,用于确定CSV文件的第一行是否是包含字段名称的标题行
  • 'header':如果CSV文件没有标题,您可以在其中提供。如果同时提供了'header''hasHeader',则'header'选项优先
  • 'inputEncoding':CSV文件的编码。默认为UTF-8
  • 'outputEncoding':读取文件时返回的数据的编码。如果'inputEncoding''outputEncoding'不同,则读取器会自动使用mbstring进行转换
  • 'delimiter':CSV分隔符
  • 'enclosure':CSV封装符
  • 'ignoreEmptyLines':如果设置为true(默认值),则读取器会静默地忽略空行。否则,如果遇到空行,将引发异常

自动字段处理

读取器还可以将格式化函数应用到您的CSV字段上。

use Csv\Reader;

$reader = new Reader($file, array(
    'hasHeader' => true,
    'inputEncoding' => 'ISO-8859-15',
    'outputEncoding' => 'UTF-8',
    'delimiter' => ';'
));
$reader->registerFormatter('birthdate', function($date) {
    return preg_replace('/^([0-9]+)-([0-9]+)-([0-9]+)$/', '$3/$2/$1', $date);
});

foreach ($reader as $line) {
    echo $line['birthdate']; // will echo 12/05/1972 for the first line
}