rdx/csv-mapper
Composer 安装命令:
composer require rdx/csv-mapper
包简介
Extends league/csv with mappers and exceptions
README 文档
README
Uses league\csv for reading CSV. Adds record & column mapping.
The first line is always used as header. You don't have to call setHeaderOffset(0).
In all examples, $reader is iterated, not queried with a Statement:
foreach ( $reader as $record ) {
// $record is done, no more processing needed
print_r($record);
}
Record mappers
To keep only certain columns, and discard the rest, use the KeepColumnsMapper:
$reader = \rdx\csvmapper\Reader::createFromPath($file);
$reader->addMapper(new KeepColumnsMapper(['firstname', 'lastname', 'email']));
Create your own record mapper by implementing RecordMapper:
class AddTimestampMapper implements RecordMapper {
protected $time;
public function __construct( $time ) {
$this->time = $time;
}
public function map( array $record, $index ) {
$record['timestamp'] = $this->time;
return $record;
}
}
$reader->addMapper(new AddTimestampMapper(time()));
Require columns
Require columns before processing iterating through the rows:
$reader = \rdx\csvmapper\Reader::createFromPath($file);
try {
$reader->requireColumns(['email']);
}
catch ( MissingColumnsException $ex ) {
echo implode(', ', $ex->getColumns());
}
Column mappers
If several columns in the same row have the same mapping, use the ColumnsMapper record mapper with the ColumnMapper interface.
To format several date fields with your own date formatter:
class DateFormatMapper implements ColumnMapper {
public function map( array $record, $column, $index, $unset ) {
$value = trim($record[$column]);
$date = my_custom_date_maker($value);
if ( !$date ) {
// Invalid = NIL
return null;
// Invalid = skip field (remove from $record)
return $unset;
// Invalid = user error
throw new LineException($index, "Invalid date: '$value'");
}
return $date;
}
}
try {
$reader = \rdx\csvmapper\Reader::createFromPath($file);
$reader->addMapper(new ColumnsMapper(new DateFormatMapper(), ['birthdate', 'created_on', 'valid_until']));
}
catch ( LineException $ex ) {
echo $ex->getMessage();
print_r($ex->getRecord($reader));
}
This will run the DateFormatMapper max 3 times for every row. The mapper runs only for fields that exist in $record.
If you want to make a field from nothing, use RecordMapper to alter the record. ColumnMapper only alters/unsets columns.
rdx/csv-mapper 适用场景与选型建议
rdx/csv-mapper 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 94 次下载、GitHub Stars 达 0, 最近一次更新时间为 2018 年 06 月 26 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 rdx/csv-mapper 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 rdx/csv-mapper 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 94
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 12
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-06-26