如何在 txt 文件中保存 bash 颜色的彩色文本?

How to save colored text with bash color in txt file?

我不知道如何正确编写此代码。

我有这样的代码:

$hasil = "\e[1;42mGreen Text";
$fp = fopen('data.txt', 'w');
fwrite($fp, $hasil . "\r\n");
fclose($fp);

我希望彩色文本存储在 data.txt 中。

这样的话,不会变成彩色文字,而是把代码保存成文字

$hasil = "<a style='color:green'>Text</a>";
$fp = fopen('data.html', 'w');
fwrite($fp, $hasil . "\r\n");
fclose($fp);

将数据保存到 html 文件后,在浏览器中打开它

或检查另一个例子

$output = convertBash('[1;42m Text');
echo $output;
//
// Converts Bashoutput to colored HTML
//
function convertBash($code) {
    $dictionary = array(
        '[1;30m' => '<span style="color:black">',
        '[1;31m' => '<span style="color:red">', 
        '[1;42m' => '<span style="color:green">',   
        '[1;33m' => '<span style="color:yellow">',
        '[1;34m' => '<span style="color:blue">',
        '[1;35m' => '<span style="color:purple">',
        '[1;36m' => '<span style="color:cyan">',
        '[1;37m' => '<span style="color:white">',
        '[m'   => '</span>'
    );
    $htmlString = str_replace(array_keys($dictionary), $dictionary, $code);
    return $htmlString;
}