DELAEMON BLOG

Live as if you were to die tomorrow. Learn as if you were to live forever.

PHPで色付きdump

書きなぐり

<?php
//  echo -e '\e[VALUE[;VALUE..]mSTRINGS\e[m'
/*
    Text attributes
    0   All attributes off
    1   Bold on
    4   Underscore (on monochrome display adapter only)
    5   Blink on
    7   Reverse video on
    8   Concealed on

    Foreground colors
    30  Black
    31  Red
    32  Green
    33  Yellow
    34  Blue
    35  Magenta
    36  Cyan
    37  White

    Background colors
    40  Black
    41  Red
    42  Green
    43  Yellow
    44  Blue
    45  Magenta
    46  Cyan
    47  White
 */

$output = null;
$indent = null;
function color($value = null)
{
    global $output;
    global $indent;
    switch (true) {
    case is_int($value):
        $type = '(int)';
        $color = 36; // Cyan
        break;
    case is_string($value):
        $type = '(str)';
        $color = 31; // Red
        break;
    case is_bool($value):
        $type = '(bool)';
        $color = 32; // Green
        $value = $value ? 'true' : 'false';
        break;
    case is_array($value):
        $output .= "$indent(array) => [\n";
        $indent .= "  ";
        foreach ($value as $v) {
            color($v);
        }
        $indent  = substr($indent , 0 , strlen($indent) - 2);
        $output .= "$indent]\n";
        return;
    case is_object($value):
        break;
    default:
        if (is_null($value)) {
            $type = '(null)';
            $value = 'null';
        }
        $color = 33; // Yellow
        break;
    }
    $output .= sprintf("\e[%dm%s%s %s \e[m\n", $color, $indent, $type, $value);
}

color(123);
color('abc');
color(true);
color();
color([1,'1',false]);
color([[1,2,3], ['a', 'b', 'c'], [true, false, null]]);

echo $output . "\n";

こんな感じ
f:id:delaemon:20150207184846p:plain