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

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;
}

Tim Bernhard

Mein Name ist Tim Bernhard, geboren bin ich am 2. August 1996. Ich besuchte die Kantonsschule in Wiedikon und schloss diese im Frühling 2015 ab. Als Maturaarbeit habe ich meine Leidenschaft für Programmiertechnische Projekte mit Hoffnungen für die Zukunft verbunden und das Unternehmen Bernhard Webstudio gegründet.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.