PHPackages                             chernegasergiy/table-magic - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [CLI &amp; Console](/categories/cli)
4. /
5. chernegasergiy/table-magic

ActiveLibrary[CLI &amp; Console](/categories/cli)

chernegasergiy/table-magic
==========================

A PHP library for creating and manipulating tables in a console output format.

v2.0.0(9mo ago)038LicenseRef-CSSM-Unlimited-2.0PHPPHP ^7.4 || ^8.2CI passing

Since Oct 19Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/ChernegaSergiy/table-magic)[ Packagist](https://packagist.org/packages/chernegasergiy/table-magic)[ RSS](/packages/chernegasergiy-table-magic/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (10)Dependencies (2)Versions (11)Used By (0)

[![table-magic](public/logo-squircle.svg)](public/logo-squircle.svg)table-magic
===========

[](#table-magic)

*A powerful and flexible PHP library for creating and manipulating tables in console output.*

[![Latest Stable Version](https://camo.githubusercontent.com/28f88684e97f50b7de1f6cec22cfc31d281ada51e55b13c29c208c430b0072c1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636865726e6567617365726769792f7461626c652d6d616769632e7376673f6c6162656c3d5061636b6167697374266c6f676f3d7061636b6167697374)](https://packagist.org/packages/chernegasergiy/table-magic)[![Total Downloads](https://camo.githubusercontent.com/820877ca5420b14259430859d69bdebfd606372e7855525ab885fbf583d896d0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636865726e6567617365726769792f7461626c652d6d616769632e7376673f6c6162656c3d446f776e6c6f616473266c6f676f3d7061636b6167697374)](https://packagist.org/packages/chernegasergiy/table-magic)[![Tests](https://camo.githubusercontent.com/e55a8f66152daac2368cc3f84b94bb498d1e4b9c207bd0ccc5c426b20651f56f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f436865726e6567615365726769792f7461626c652d6d616769632f706870756e69742e796d6c3f6c6162656c3d5465737473266c6f676f3d676974687562)](https://github.com/ChernegaSergiy/table-magic/actions/workflows/phpunit.yml)[![Test Coverage](https://camo.githubusercontent.com/5986534dcca2f1d8e7d313ef4df51168bd96068ec9407b69323c836a8eb54d1d/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f436865726e6567615365726769792f7461626c652d6d616769633f6c6162656c3d54657374253230436f766572616765266c6f676f3d636f6465636f76)](https://app.codecov.io/gh/ChernegaSergiy/table-magic)[![Static Analysis](https://camo.githubusercontent.com/19aeeea30e608c860d719b2da35aef8bb10165ebd344ec92354e27209c07dc36/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f436865726e6567615365726769792f7461626c652d6d616769632f7068707374616e2e796d6c3f6c6162656c3d5048505374616e266c6f676f3d676974687562)](https://github.com/ChernegaSergiy/table-magic/actions/workflows/phpstan.yml)[![License](https://camo.githubusercontent.com/ee3a34c0537d4c5d879dbb7491ca731036e62f0dbcc6c692651244855b802e4b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f636865726e6567617365726769792f7461626c652d6d616769632e7376673f6c6162656c3d4c6963656e6365266c6f676f3d6f70656e2d736f757263652d696e6974696174697665)](https://packagist.org/packages/chernegasergiy/table-magic)

[Features](#features) · [Installation](#installation) · [Usage](#usage) · [Styling](#table-styling) · [Import &amp; Export](#importing-data) · [Contributing](#contributing)

---

**table-magic** is a powerful and flexible PHP library designed for creating and manipulating tables in console output. Inspired by Python's PrettyTable, table-magic empowers developers to effortlessly display tabular data with customizable alignment, sorting, and styling options.

Features
--------

[](#features)

- **Easy Table Creation**: Quickly create tables with headers and rows.
- **Dynamic Row Addition**: Add rows easily with support for automatic column width adjustment.
- **Customizable Column Alignments**: Align columns to the left, right, or center.
- **UTF-8 Support**: Properly display non-ASCII characters.
- **Sorting Capability**: Sort tables by any column in ascending or descending order.
- **Export and Import Options**: Import data from CSV, JSON, XML, and Markdown formats, and export to HTML, CSV, JSON, XML, and Markdown using a flexible, object-oriented approach with dedicated importer and exporter classes.
- **Customizable Table Styles**: Apply various predefined styles or define your own for unique table appearances.
- **Terminal Interaction**: Paginate through large tables in the console.

Repository Structure
--------------------

[](#repository-structure)

Here is the updated structure of the core `src/` directory:

```
src/
\-- /
    +-- Table.php
    +-- TableExporter.php
    +-- TableImporter.php
    +-- TableStyle.php
    +-- TableStyleRegistry.php
    +-- TerminalInteraction.php
    +-- Interfaces/                # Defines contracts for importers and exporters
    |   +-- TableImporterInterface.php
    |   \-- TableExporterInterface.php
    +-- Importers/                 # Concrete implementations for importing various formats
    |   +-- CsvTableImporter.php
    |   +-- JsonTableImporter.php
    |   +-- MarkdownTableImporter.php
    |   \-- XmlTableImporter.php
    \-- Exporters/                 # Concrete implementations for exporting to various formats
        +-- CsvTableExporter.php
        +-- HtmlTableExporter.php
        +-- JsonTableExporter.php
        +-- MarkdownTableExporter.php
        \-- XmlTableExporter.php

```

Installation
------------

[](#installation)

You can install using Composer:

```
composer require chernegasergiy/table-magic
```

Usage
-----

[](#usage)

Here's a quick example to get you started with :

```
require_once 'vendor/autoload.php';

use ChernegaSergiy\TableMagic\Table;

// Define headers and alignments
$headers = ['Employee ID', 'Name', 'Department', 'Performance Score', 'Review Date'];
$alignments = [
    'Employee ID' => 'r',
    'Performance Score' => 'r',
    'Review Date' => 'c',
];

// Create a new Table instance
$table = new Table($headers, $alignments);

// Add rows to the table
$table->addRow([1001, 'Alice Thompson', 'Marketing', 85, '2024-06-15']);
$table->addRow([1002, 'Brian Lee', 'Sales', 90, '2024-06-18']);
$table->addRow([1003, 'Carol Martinez', 'Engineering', 88, '2024-06-20']);

// Display the table
echo $table;

// Sort the table by 'Performance Score' (descending order)
$table->sortTable('Performance Score', 'desc');
echo "\n\nSorted by Performance Score (Descending):\n";
echo $table;
```

This will output:

```
+-------------+----------------+-------------+-------------------+-------------+
| Employee ID |      Name      | Department  | Performance Score | Review Date |
+-------------+----------------+-------------+-------------------+-------------+
|        1001 | Alice Thompson | Marketing   |                85 | 2024-06-15  |
|        1002 | Brian Lee      | Sales       |                90 | 2024-06-18  |
|        1003 | Carol Martinez | Engineering |                88 | 2024-06-20  |
+-------------+----------------+-------------+-------------------+-------------+

Sorted by Performance Score (Descending):
+-------------+----------------+-------------+-------------------+-------------+
| Employee ID |      Name      | Department  | Performance Score | Review Date |
+-------------+----------------+-------------+-------------------+-------------+
|        1002 | Brian Lee      | Sales       |                90 | 2024-06-18  |
|        1003 | Carol Martinez | Engineering |                88 | 2024-06-20  |
|        1001 | Alice Thompson | Marketing   |                85 | 2024-06-15  |
+-------------+----------------+-------------+-------------------+-------------+

```

Table Styling
-------------

[](#table-styling)

The library offers extensive customization options for its appearance through a flexible styling system. You can apply various predefined styles or define your own custom ones to match your application's aesthetic.

### Predefined Styles

[](#predefined-styles)

It comes with several built-in styles, including: `default`, `compact`, `dots`, `rounded`, `unicode-single-line`, `unicode-double-line`, `github-markdown`, `reddit-markdown`, `restructured-text-grid`, and `restructured-text-simple`.

Here's an example demonstrating some of these styles, along with a custom one:

```
require_once 'vendor/autoload.php';

use ChernegaSergiy\TableMagic\Table;
use ChernegaSergiy\TableMagic\TableStyle;
use ChernegaSergiy\TableMagic\TableStyleRegistry;

$table = new Table(
    ['Product', 'Quantity', 'Price'],
    [
        'Quantity' => 'c', // Center align Quantity
        'Price' => 'r'     // Right align Price
    ]
);
$table->addRow(['Laptop', 2, 1200.50]);
$table->addRow(['Mouse', 5, 25.00]);
$table->addRow(['Keyboard', 1, 75.99]);

echo "Default Style:\n";
$table->setStyle('default');
echo $table;

echo "\nCompact Style:\n";
$table->setStyle('compact');
echo $table;

echo "\nUnicode Single Line Style:\n";
$table->setStyle('unicode-single-line');
echo $table;

// Define and apply a custom style
$custom_style = new TableStyle(
    '¦', // Vertical separator (light vertical bar)
    ['╭', '─', '┬', '╮'], // Top border (rounded corners)
    ['├', '─', '┼', '┤'], // Header separator (light lines)
    ['¦', '┄', '┼', '¦'], // Row separator (dashed horizontal, light vertical)
    ['╰', '─', '┴', '╯']  // Bottom border (rounded corners)
);
TableStyleRegistry::register('custom-fancy', $custom_style);

echo "\nCustom 'Fancy' Style:\n";
$table->setStyle('custom-fancy');
echo $table;
```

This will output:

```
Default Style:
+----------+----------+--------+
| Product  | Quantity |  Price |
+----------+----------+--------+
| Laptop   |    2     | 1200.5 |
| Mouse    |    5     |     25 |
| Keyboard |    1     |  75.99 |
+----------+----------+--------+

Compact Style:
  Product    Quantity    Price
 ---------- ---------- --------
  Laptop        2       1200.5
  Mouse         5           25
  Keyboard      1        75.99

Unicode Single Line Style:
┌──────────┬──────────┬────────┐
│ Product  │ Quantity │  Price │
├──────────┼──────────┼────────┤
│ Laptop   │    2     │ 1200.5 │
│ Mouse    │    5     │     25 │
│ Keyboard │    1     │  75.99 │
└──────────┴──────────┴────────┘

Custom 'Fancy' Style:
╭──────────┬──────────┬────────╮
¦ Product  ¦ Quantity ¦  Price ¦
├──────────┼──────────┼────────┤
¦ Laptop   ¦    2     │ 1200.5 ¦
¦ Mouse    ¦    5     │     25 ¦
¦ Keyboard │    1     │  75.99 ¦
╰──────────┴──────────┴────────╯

```

### Importing Data

[](#importing-data)

Data can be imported using the `TableImporter` factory, which delegates to specific importer classes based on the format:

```
use ChernegaSergiy\TableMagic\TableImporter;

$importer = new TableImporter();
$csv_data = "Name,Age\nAlice,30\nBob,25";
$table_from_csv = $importer->import($csv_data, 'csv');

$json_data = '{"headers":["Name","Age"],"rows":[["Charlie",30],["David",25]]}';
$table_from_json = $importer->import($json_data, 'json');

$xml_data = 'NameAgeEve30';
$table_from_xml = $importer->import($xml_data, 'xml');

$markdown_data = "| Name | Age |\n|:---|---:|\n| Frank | 40 |\n| Grace | 35 |";
$table_from_markdown = $importer->import($markdown_data, 'markdown');

// You can also directly use specific importer classes:
use ChernegaSergiy\TableMagic\Importers\CsvTableImporter;
$csv_importer = new CsvTableImporter();
$table_direct_csv = $csv_importer->import($csv_data);
```

### Exporting Data

[](#exporting-data)

Tables can be exported using the `TableExporter` factory, which delegates to specific exporter classes based on the format:

```
use ChernegaSergiy\TableMagic\TableExporter;

$table_to_export = new Table(['Col1'], ['Val1']);
$exporter = new TableExporter($table_to_export);

$html_output = $exporter->export('html');
$csv_output = $exporter->export('csv');
$json_output = $exporter->export('json');
$xml_output = $exporter->export('xml');
$markdown_output = $exporter->export('markdown');

// You can also directly use specific exporter classes:
use ChernegaSergiy\TableMagic\Exporters\HtmlTableExporter;
$html_exporter = new HtmlTableExporter();
$direct_html_output = $html_exporter->export($table_to_export);
```

### Terminal Interaction

[](#terminal-interaction)

For large datasets, you can interactively paginate through the table:

```
use ChernegaSergiy\table-magic\TerminalInteraction;

$terminal_interaction = new TerminalInteraction($table);
$terminal_interaction->run();
```

An example script demonstrating terminal interaction is available at `examples/run_terminal_interaction.php`.

Contributing
------------

[](#contributing)

Contributions are welcome and appreciated! Here's how you can contribute:

1. Fork the project
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

Please make sure to update tests as appropriate and adhere to the existing coding style.

License
-------

[](#license)

This library is licensed under the CSSM Unlimited License v2.0 (CSSM-ULv2). See the [LICENSE](LICENSE) file for details.

Acknowledgments
---------------

[](#acknowledgments)

- Inspired by the Python [PrettyTable](https://github.com/jazzband/prettytable) library

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance73

Regular maintenance activity

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~41 days

Recently: every ~87 days

Total

10

Last Release

297d ago

Major Versions

v1.3.0 → v2.0.02025-10-25

### Community

Maintainers

![](https://www.gravatar.com/avatar/e2471bdadcf4a5ea969fe763a72d03fb46525b59a7e4cedc3ed4d855029e7785?d=identicon)[ChernegaSergiy](/maintainers/ChernegaSergiy)

---

Top Contributors

[![ChernegaSergiy](https://avatars.githubusercontent.com/u/60980650?v=4)](https://github.com/ChernegaSergiy "ChernegaSergiy (132 commits)")

---

Tags

asciiascii-tablesconsole-table-printerphp-libraryphp7php8prettytable

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/chernegasergiy-table-magic/health.svg)

```
[![Health](https://phpackages.com/badges/chernegasergiy-table-magic/health.svg)](https://phpackages.com/packages/chernegasergiy-table-magic)
```

###  Alternatives

[illuminate/console

The Illuminate Console package.

13046.6M7.4k](/packages/illuminate-console)[styleci/cli

The CLI tool for StyleCI

71477.7k9](/packages/styleci-cli)[winbox/args

Windows command-line formatter

20722.5k21](/packages/winbox-args)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
