0
1

PHPアプリケーションで、標準出力の文字の色やフォーマットをカスタマイズする

Last updated at Posted at 2024-06-02

前提

Symfonyがインストールされていること。(LaravelやCakePHPなどにはインストールされているはずです。)

概要

SymfonyのConsoleOutputクラスを使って、簡単に標準出力のフォーマットを指定できたのでその方法と具体例を軽く紹介します。

具体例

$output = new \Symfony\Component\Console\Output\ConsoleOutput();

$output->writeln('<info>これは情報メッセージです。</info>');
$output->writeln('<comment>これはコメントメッセージです。</comment>');
$output->writeln('<question>これは質問メッセージです。</question>');
$output->writeln('<error>これはエラーメッセージです。</error>');
$output->writeln('<fg=cyan>これはカスタムカラーのメッセージです。</>');
$output->writeln('<bg=blue;fg=white>これは青い背景に白い文字のメッセージです。</>');
$output->writeln('<options=bold>これは太字のメッセージです。</>');
$output->writeln('<options=underscore>これは下線付きのメッセージです。</>');
$output->writeln('<options=reverse>これは反転したメッセージです。</>');
$output->writeln('<fg=black;bg=yellow>これは黄色い背景に黒い文字のメッセージです。</>');
$output->writeln('<fg=green;bg=black;options=bold>黒い背景に緑色の太字のテキスト。</>');

CLIで実行すると下記のように出力されます。

スクリーンショット 2024-06-03 0.02.01.png

fg={color} で文字の色、bg={color} で背景色を指定できます。
また、options=bold で太文字にできます。

追記(2024-06-04)

下記のように書くと、標準エラー出力もできます。

$output = new \Symfony\Component\Console\Output\StreamOutput(\STDERR);
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1