How to Encode an SVG for the `src`-Attribute using PHP

Tim Bernhard

PHPTutorialimageSVG

As SVGs should preferably not be base64 encoded when setting them on an ``-tag src-attribute, the suggested alternative is to URL-encode them. The standard PHP urlencode function unfortunately is not suitable for this task, as the resulting value is not interpreted by any browser as a valid SVG image. Instead, the function rawurlencode has to be used. Took me some time to realize.

As soon as you get this, you can also take over some other optimizations; maybe get inspired by Taylor Hunts mini-svg-uri to decode some characters manually to improve the overall size. A final function could possibly look like this:

function svgUrlEncode($svgPath) {
        $data = \file_get_contents($svgPath);
        $data = \preg_replace('/\v(?:[\v\h]+)/', ' ', $data);
        $data = \str_replace('"', "'", $data);
        $data = \rawurlencode($data);
        // re-decode a few characters understood by browsers to improve compression
        $data = \str_replace('%20', ' ', $data);
        $data = \str_replace('%3D', '=', $data);
        $data = \str_replace('%3A', ':', $data);
        $data = \str_replace('%2F', '/', $data);
        return $data;
}
Webmentions

No webmentions found for this page.