# Compress svg files in PHP

I wrote something to "compress" svg files. The svg files I am using often have comments and empty <g> tags, and I want to remove them. My main goal is not the speed of the compression, but the size of the compressed svg file.

Here is an example svg file: https://image.flaticon.com/icons/svg/222/222436.svg

And here is the code I am using:

public function compress($svg) {$svg = preg_replace('/<!--.*-->/', '', $svg);$svg = preg_replace('/<g>[\n\r\s]*<\/g>/', '', $svg);$svg = preg_replace('/\n/', ' ', $svg);$svg = preg_replace('/\t/', ' ', $svg);$svg = preg_replace('/\s\s+/', ' ', $svg);$svg = str_replace('> <', '><', $svg);$svg = str_replace(';"', '"', $svg); return$svg;
}

1. Do you see any dangers here, perhaps this could ruin some svg files?
2. Is there something I could do to compress the file even more?
3. Is there any way to speed this up?

SVG is structured data and should therefore not require regex to work with it. I would suggest that you work with either an XML or SVG-specific library in PHP which would let you parse in the input SVG, remove any unwanted nodes and then render it back out.

Here is a starting point for common PHP tools for working with XML that should be able to do what you want.

This also looks like a library that could meet your needs.

$iconfile = new DOMDocument();$iconfile->load($source);$svg = $iconfile->saveHTML($iconfile->getElementsByTagName('svg')[0]);
$svg = preg_replace('/<!--.*-->/', '',$svg);
$svg = preg_replace('/<g>[\n\r\s]*<\/g>/', '',$svg);
$svg = preg_replace('/\n/', ' ',$svg);
$svg = preg_replace('/\t/', ' ',$svg);
$svg = preg_replace('/\s\s+/', ' ',$svg);
$svg = str_replace('> <', '><',$svg);
$svg = str_replace(';"', '"',$svg);

echo \$svg;

• You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. – Vogel612 Nov 6 at 20:32
• Not only is this a code-only answer, there is much about these processes that can be simplified. I would not recommend this approach to anyone ...especially because I agree with Mike Brant's review/advice. – mickmackusa Nov 6 at 23:57