Using PHP and Apache to create a dynamic SVGZ file
— Written by Jonathan Ingram
Recently I needed to create an SVG image (using PHP) that could change colour depending on the hexadecimal values that my MySQL database wanted to spit out.
After tweaking the SVG code as much as I could (by cloning objects and rounding the ridiculously long float values that Inkscape creates) I managed to get the file size down to about 13KB.
However, I knew I could do much better if I could somehow compress it with SVGZ instead.
I regulary use the compression benefits of SVGZ for my static SVG files but when you need one created dynamically on the server (without the help of a program like Inkscape) then it requires a bit of a fiddle on your part.
In reality I used MySQL queries to obtain the hexadecimal colours that I needed for my script but for the purposes of this article I’ll keep this PHP example really simple.
This example would display a blue rectangle and your web browser would know immediately that it’s an SVG file (rather than a PHP file) because we’ve added a content type of image/svg+xml
to the header.
However, to display it as an SVGZ file instead we need to GZIP it (as this is essentially what Inkscape does when it creates SVGZ files).
To do this we need to use the PHP function gzencode
and to also inform the web browser that our file will be coming over in a GZIP format (otherwise the browser would spit out something that only the ancient Egyptians would understand).
The gzencode
function creates a GZIP compressed string (in our case compressing the string $svg_output
). There’s also an optional parameter that determines the level of compression that we want to apply (0 for no compression, up to 9 for maximum compression).
Depending on the setup of your Apache server (and whether you’ve had experience of using SVGZ files online before) some of you will get this example working straight away. For the rest of you however, you’ll probably need to add the following lines to your .htaccess file.
The first line informs the server that both SVG and SVGZ files should be recognised with the image/svg+xml
MIME type, whilst the second line is used by the client to determine how to decode SVGZ files.
There you go, it’s all done.
Although if you’re really fussy (like me) then you can also add some additional lines to your .htaccess file so that your image.php file can be found via the name of image.svgz instead.
The result of all this meant that my original 13KB file had shrunk down to just 1KB.
I’ll no doubt come back to this in the future, to see if I can shrink it down any further, but for now I’m quite happy with the 92% improvement.