0

I'm fetching output from the exec() function and I would like to have some syntax highlighting in the results.

Raw output

Current output is raw:

* [35mmanu[m/etc/init.d/mast: line 105: /var/log/mast/mast-all.log: Permission denied 

Text such as [35m are color highlighting in shell context.

Goal

I want to do it in HTML, I already have a colored shell script.

highlighted syntax

Édouard Lopez
  • 40,270
  • 28
  • 126
  • 178

2 Answers2

1

The question A library to convert ANSI escapes (terminal formatting/color codes) to HTML has an answer to this question.

Solution

aha is a Ansi to HTML Adapter written in C. It's available in an Ubuntu package and on github theZiz/aha.

My code is then simply:

   exec("$command | aha", $output, $exitCode);
   foreach($output as $k => $line) {
       if ($line == '1') { continue; }
       echo "$line";
   }

Description

   aha takes SGR-colored Input and prints W3C conform HTML-Code.
   aha reads the Input from a file or stdin and writes HTML-Code to stdout.

There is some nice options:

  • --black , -b: Black Background and white "standard color"
  • --word-wrap , -w: Wrap long lines in the html file. This works with CSS3 supporting browsers as well as many older ones.
  • --no-header , -n: Don't include header into generated HTML, useful for inclusion in full HTML files.
Community
  • 1
  • 1
Édouard Lopez
  • 40,270
  • 28
  • 126
  • 178
1

You can also do it in pure PHP thanks to symfony. using ansi-to-html library. It has no dependency, so it is not required to use symfony.

You can install it manually by coping SensioLabs\AnsiConverter\AnsiToHtmlConverte.phpin your source folder or using composer composer require sensiolabs/ansi-to-html

After that just a

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

use SensioLabs\AnsiConverter\AnsiToHtmlConverter;

$converter = new AnsiToHtmlConverter();

$html = $converter->convert($ansi);