Colorizing Windows command line output from PHP

To output colored text in bash, you use ANSI escape sequences.

How do you output colored text on a Windows command line, specifically from PHP?


Download dynwrap.dll from : http://www.script-coding.com/dynwrap95.zip

Then extract it to %systemroot%system32 directory and then run following command in command line:

regsvr32.exe "%systemroot%system32dynwrap.dll"

You'll get a success message which means dynwrap.dll is registered.

Then you can use it this way :

$com = new COM('DynamicWrapper');

// register needed features
$com->Register('kernel32.dll', 'GetStdHandle', 'i=h', 'f=s', 'r=l');
$com->Register('kernel32.dll', 'SetConsoleTextAttribute', 'i=hl', 'f=s', 'r=t');

// get console handle
$ch = $com->GetStdHandle(-11);

some example:

$com->SetConsoleTextAttribute($ch, 4);
echo 'This is a red text!';
$com->SetConsoleTextAttribute($ch, 7);
echo 'Back to normal color!';

colors codes:
7 => default
0 => black
1 => blue
2 => green
3 => aqua
4 => red
5 => purple
6 => yellow
7 => light gray
8 => gray
9 => light blue
10 => light green
11 => light aqua
12 => light red
13 => light purple
14 => light yellow
15 => white


ANSI escape codes are unfortunately not available in Windows Command Prompt, natively.

However you can try:

  • patching cmd.exe with ansihack.exe http://gynvael.coldwind.pl/?id=130&lang=en :)
  • http://adoxa.110mb.com/ansicon/index.html
  • On bash shell it works like a charm and there is even a php lib for that: http://sourceforge.net/projects/milcovlib/

    If it's an overkill for you you can try this:

    echo "33[31mred33[37mrn";
    echo "33[32mgreen33[37mrn";
    echo "33[41;30mblack on red33[40;37mrn";
    

    Here is the list of bash color codes:

    $black = "33[0;30m";
    $darkgray = "33[1;30m";
    $blue = "33[0;34m";
    $lightblue = "33[1;34m";
    $green = "33[0;32m";
    $lightgreen = "33[1;32m";
    $cyan = "33[0;36m";
    $lightcyan = "33[1;36m";
    $red = "33[0;31m";
    $lightred = "33[1;31m";
    $purple = "33[0;35m";
    $lightpurple = "33[1;35m";
    $brown = "33[0;33m";
    $yellow = "33[1;33m";
    $lightgray = "33[0;37m";
    $white = "33[1;37m";
    

    It appears that using plain escape codes won't work on the Windows command prompt. The answers on the other SO questions related to this say that you need to use the Win32 API. A Win32 API library does exist for PHP, however the documentation does have a large red section warning that it is experimental . YMMV.

    链接地址: http://www.djcxy.com/p/87388.html

    上一篇: 在我的android应用程序中处理textview链接点击

    下一篇: 着色来自PHP的Windows命令行输出