Rendering the Magento 2 console command output as a table

#magento2 #snippet

Here is a quick example of how to render the Magento 2 console command output as a table. This can be useful in a number of situations where the resulting data is tabular.

Magento 2 CLI Table Output

To achieve this, Symfony’s Table helper class will be used. There is no difference whether you use this class in Magento or Symfony, so you can check the official docs to see all the features: https://symfony.com/doc/current/components/console/helpers/table.html


Nevertheless, here is an example in Magento’s context. The example assumes that you have your module registered and the command defined in di.xml file:

<?php

declare(strict_types=1);

namespace ArchApps\Example\Console\Command;

use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class TableOutputExample extends Command
{
    /**
     * Bare minimum required to configure the command
     */
    protected function configure()
    {
        $this->setName('archapps:example:table-output');
    }

    /**
     * Executes the command and prints output as a table
     */
    protected function execute(
        InputInterface $input,
        OutputInterface $output
    ): int {
        $table = new Table($output);

        // Defining the table headers (this is optional)
        $table->setHeaders(['Column 1', 'Column 2', 'Column 3']);

        // Adding three rows with example data
        $table->addRow(['Row 1, Column 1', 'Row 1, Column 2', 'Row 1, Column 3']);
        $table->addRow(['Row 2, Column 1', 'Row 2, Column 2', 'Row 2, Column 3']);
        $table->addRow(['Row 3, Column 1', 'Row 3, Column 2', 'Row 3, Column 3']);

        // Rendering the table
        $table->render();

        return Command::SUCCESS;
    }
}

That’s it. Quite simple! Cheers!

⇐ All Blog Posts
Tweet Share