PHP code example of alexskrypnyk / csvtable

1. Go to this page and download the library: Download alexskrypnyk/csvtable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alexskrypnyk / csvtable example snippets


$csv = file_get_contents($csv_file);
print (new CsvTable($csv))->format();

print (CsvTable::fromFile($file))->format();

$table = new CsvTable($csv);
$table->parse();

// ['col11', 'col12', 'col13']
print_r($table->getHeader());

// [['col21', 'col22', 'col23'], ['col31', 'col32', 'col33']]
print_r($table->getRows());

// Parse semicolon-separated content.
$table = new CsvTable($csv_semicolon, ';');

// The same, reading from a file.
$table = CsvTable::fromFile($file_semicolon, ';');

$table = new CsvTable($csv_semicolon, ';');

// Comma-separated output.
print $table->format();

// Semicolon-separated output.
print $table->format(NULL, ['separator' => ';']);

print (CsvTable::fromFile($file))->format('table');

print (CsvTable::fromFile($file))->withoutHeader()->format('table');

print (CsvTable::fromFile($file))->format('markdown_table');

print (CsvTable::fromFile($file))
  ->format('markdown_table', ['header_separator' => '=']);

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));
});

print (CsvTable::fromFile($file))
  ->withoutHeader()
  ->format(CustomFormatter::class);

$formatter_options = ['option1' => 'value1', 'option2' => 'value2'];

print (CsvTable::fromFile($file))
  ->withoutHeader()
  ->format([CustomFormatter::class, 'customFormat'], $formatter_options);

print (CsvTable::fromFile($file))
  ->columnOrder(['City', 'Name'])
  ->format('markdown_table');

print (CsvTable::fromFile($file))
  ->onlyColumns(['Name', 'City'])
  ->format('markdown_table');

print (CsvTable::fromFile($file))
  ->withoutColumns(['Age', 'Country'])
  ->format('markdown_table');

// Using indices.
print (CsvTable::fromFile($file))->columnOrder([2, 0])->format();

// Using mixed names and indices.
print (CsvTable::fromFile($file))->onlyColumns(['Name', 2])->format();

print (CsvTable::fromFile($file))
  ->withoutColumns(['Age'])
  ->columnOrder(['Country', 'City'])
  ->format('markdown_table');

$table = CsvTable::fromFile($file);

// Apply and use transformations.
$table->columnOrder(['City', 'Name']);
print $table->format();

// Reset and format without transformations.
print $table->resetColumns()->format();