fusonic/csv-reader
最新稳定版本:0.5.2
Composer 安装命令:
composer require fusonic/csv-reader
包简介
Map data from CSV files to typed PHP models.
README 文档
README
CSV Reader is a powerful library for PHP 8 that allows you to map data from CSV files to a strongly typed data model. It does this by utilizing PHP 8's typed properties / arguments and automatically converts string values to the types defined for your class fields.
Install
Use composer to install the lib from Packagist.
composer require fusonic/csv-reader
Requirements:
- PHP 8.2+
Usage
Just define a class that represents your CSV's data structure and use the IndexMapping or TitleMapping attributes to define the mapping. You don't have to map all the columns, just the ones you need on your model.
class Foo { #[TitleMapping('Price')] public float $price; #[TitleMapping('Price')] public function setPrice(float $value): void { // Not implemented } }
Now use the CsvReader class to convert CSV data to your object model:
$reader = new CsvReader('myfile.csv'); foreach ($reader->readObjects(Foo::class) as $item) { var_dump($item); }
Hint: You can also pass a resource instead of a file's path to CsvReader. This way you can also access files from remote filesystems, for example if you are using league/flysystem.
Supported types
intfloatstringbool(usesfilter_var()withFILTER_VALIDATE_BOOLEANand supports values likeon,true,1)DateTimeDateTimeInterfaceDateTimeImmutable
If you choose to use a **nullable type like ?string``** it will be mapped as null` if the CSV value is an empty string or 'null' (case insensitive).
Options
Refer to the CsvReaderOptions class to learn about options.
IntlValueConverter
If you need to unserialize floating point numbers from a specific culture, you can use the IntlValueConverter like this:
$options = new CsvReaderOptions(); $options->valueConverter = new IntlValueConverter('de-AT'); $reader = new CsvReader($options);
Note: parsing German date format is done implicitely by the default ValueConverter implementation since PHP supports passing German date formats to DateTimeInterface derivates.
Contributing
This is a subtree split of fusonic/php-extensions repository. Please create your pull requests there.
统计信息
- 总下载量: 85.09k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 10
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-02-09