alexskrypnyk / csvtable
PHP class to work with CSV as a table and export it as Markdown.
Fund package maintenance!
Patreon
Installs: 3 942
Dependents: 3
Suggesters: 0
Security: 0
Stars: 3
Watchers: 2
Forks: 1
Open Issues: 3
Requires
- php: >=8.2
Requires (Dev)
- drupal/coder: ^8.3
- ergebnis/composer-normalize: ^2.44
- phpmd/phpmd: ^2.15
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.1
- rector/rector: ^1.0.0
This package is auto-updated.
Last update: 2024-12-12 10:37:48 UTC
README
PHP class to parse and format CSV content
Features
- Single-file class to manipulate CSV table.
- Formatters for CSV, text table and Markdown table.
- Support for a custom formatter.
Installation
composer require alexskrypnyk/csvtable
Usage
Given a CSV file with the following content:
col11,col12,col13
col21,col22,col23
col31,col32,col33
From string
$csv = file_get_contents($csv_file); // Format using the default formatter. print (new CsvTable($csv))->format();
will produce identical CSV content by default:
col11,col12,col13
col21,col22,col23
col31,col32,col33
From file
print (CsvTable::fromFile($file))->format();
will produce identical CSV content by default:
col11,col12,col13
col21,col22,col23
col31,col32,col33
Using text_table
formatter
print (CsvTable::fromFile($file))->format('text_table');
will produce table content:
col11|col12|col13
-----------------
col21|col22|col23
col31|col32|col33
Using text_table
formatter without a header
print (CsvTable::fromFile($file))->withoutHeader()->format('text_table');
will produce table content:
col11|col12|col13
col21|col22|col23
col31|col32|col33
Using markdown_table
formatter
print (CsvTable::fromFile($file))->format('markdown_table');
will produce Markdown table:
| col11 | col12 | col13 | |-------|-------|-------| | col21 | col22 | col23 | | col31 | col32 | col33 |
Custom formatter as an anonymous callback
print (CsvTable::fromFile($file))->format(function ($header, $rows, $options) { $output = ''; if (count($header) > 0) { $output = implode('|', $header); $output .= "\n" . str_repeat('=', strlen($output)) . "\n"; } return $output . implode("\n", array_map(static function ($row): string { return implode('|', $row); }, $rows)); });
will produce CSV content:
col11|col12|col13
=================
col21|col22|col23
col31|col32|col33
Custom formatter as a class with default format
method
print (CsvTable::fromFile($file))->withoutHeader()->format(CustomFormatter::class);
Custom formatter as a class with a custom method and options
$formatter_options = ['option1' => 'value1', 'option2' => 'value2']; print (CsvTable::fromFile($file))->withoutHeader()->format([CustomFormatter::class, 'customFormat'], $formatter_options);
Maintenance
composer install
composer lint
composer test
This repository was created using the Scaffold project template