I recently found myself needing to enforce color values in a hex code format after discovering a mix of hex codes and CSS color names in my data. The easiest way to do this was to build a static map. My application is built with PHP so I needed to get the full list of CSS color names as listed on the W3’s website into an associative PHP array.
This was my journey.
Start with the W3’s list of colors and using Chrome’s inspector, copy the HTML table.
Then, using an online HTML table-to-CSV converter, paste the table’s HTML code and download a formatted CSV. You could use a table-to-JSON converter, but CSVs are easier to manipulate and customize via something like Excel or Numbers. For me, I wanted to delete the first two columns as they are for HTML display purposes and hold no real data or value for my needs.
Once the CSV was tidied up, it was on to a CSV-to-JSON converter. Here, I chose the “hash” instead of the “array” option as I wanted a keyed/hashed list which would make it easier to target specific colors.
Last but not least, it was on to another free online too – a JSON-to-PHP array converter. True, PHP can easily parse a JSON file into an associative array, but if it’s configuration and something likely not to change ever, it’s better to just use a native array and put it in your source code.
Now I can do this:
$hex = $colors['hex']['aquamarine'];
// or
$rgb = $colors['rgb']['aquamarine'];
That’s it. It was a short walk with multiple jumps. Were there better ways to get here? Possibly, but what matters is that I got there and I’m sharing the files here in case anyone (ie: future me) finds themselves needing to translate CSS color names into hex codes or an RGB value.
Cheers!