mya-zaki/csvert

导入和导出 CSV。

v1.0.2 2019-10-30 06:37 UTC

This package is auto-updated.

Last update: 2024-09-16 08:05:07 UTC


README

配置记录对象

<?php
namespace App;

use MyaZaki\Csvert\Record;

class PostalCode extends Record
{
    public $delimiter = ',';
    public $enclosure = '"';
    public $escape = '\\';

    public $charset = 'SJIS-win';

    public $header = true;

    public $columns = [
        'Code',
        'Street',
        'City',
        'State',
    ];

    public function getAddress()
    {
        return $this->attributes['Street'] . ', ' . $this->attributes['City'] . ', ' . $this->attributes['State'];
    }
}

columns CSV 的标题字段。这些字段是记录对象的关键字。

header 外部源有标题字段。默认=true

charset
外部源的编码。
默认=UTF-8

delimiter:可选的分隔符参数设置字段分隔符(仅一个字符)。
默认=','

enclosure:可选的封装参数设置字段封装字符(仅一个字符)。
默认='"'

escape:可选的转义参数设置转义字符(最多一个字符)。空字符串 ("") 禁用专有转义机制。
默认='\'

请参考 https://php.ac.cn/manual/en/function.fgetcsv.php

解析 CSV

postal.csv

Code,Street,City,State
640941,"旭ケ丘","札幌市中央区","北海道"
600041,"大通東","札幌市中央区","北海道"
・・・

解析文件

$parser = PostalCode::parse($filepath);
$address_list = [];
$parser->walk(function ($record) use (&$address_list) { // Call user function each line
    // Given Record instance
    $address_list[] = $record['Code'] . ' ' . $record->getAddress();
});

解析字符串

$parser = PostalCode::parseString($csv_content);
$records = $parser->get(); // Get Collection
$address = $records->where('State', '北海道')->first();
var_dump($address['Code']);

保存 CSV

$writer = RecordSample::getWriter();

$collection = collect();
$collection->push(new PostalCode(['Code' => '600042', 'State' => '北海道', 'City' => '札幌市中央区', 'Street' => '大通西(1~19丁目)']));
$collection->push(new PostalCode(['Code' => '640820', 'State' => '北海道', 'City' => '札幌市中央区', 'Street' => '大通西(20~28丁目)']));

$writer->setRecords($collection);

$writer->save($filepath);