I always loved writing CLI scripts. And in PHP this is no different. I write a lot of CLI importers, scrapers, reporters, etc. And sometimes i want a bit more funk in my output then the standard black and white. When output is important i will add some colors to make things more clear. And this is not hard at all.
First of it’s probably a good thing to gather some of the available colors. A good resource is available here. Some of the colors and their corresponding codes can be found below.
Light Gray 0;37
Dark Gray 1;30
Light Blue 1;34
Light Green 1;32
Light Cyan 1;36
Light Red 1;31
Light Purple 1;35
So how do i output colors you ask? Well that’s just plain easy. It’s a bit like setting up colors in your linux PS1 env variable.
Display a line in red for instance can be simply done by ‘echoing’ from the script with some extra formatting for bash to pickup. I will try to explain everything in the line below a bit later.
So what’s going on here. First we use an escape character so we can actually define a output color. This is done with \033 (\e). Then we open the color statement with [31m. Red in this case. The “some colored text” will be the text outputted in a different color. And after that we have to close the color statement with \033[0m.
Easy as cake… that’s all!