alexskrypnyk/csvtable

PHP class to work with CSV as a table and export it as Markdown.

Fund package maintenance!
Patreon

1.0.0 2024-11-17 00:27 UTC

README

Yourproject logo

PHP class to parse and format CSV content

GitHub Issues GitHub Pull Requests Test codecov GitHub release (latest by date) LICENSE Renovate

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