dmgig
dmgig

Reputation: 4568

Use PHP to prep SVG file for use in img tag data uri

I'm using PHP. I would like to use file_get_contents to get an .svg file, and convert it for use as a data uri in an image tag. Something along these lines:

Controller:

$mylogo   = file_get_contents(FCPATH.'app/views/emails/images/mylogo.svg');

View:

<img src="data:image/svg+xml;utf8,<?= $mylogo ?>">

I need to convert it into something (base64?) as right now it is just dumping it in tags and all and though the image does appear, it makes a mess of the img tag surrounding it.

Upvotes: 6

Views: 13042

Answers (2)

Erdal G.
Erdal G.

Reputation: 2980

Solution

Controller

$encodedSVG = \rawurlencode(\str_replace(["\r", "\n"], ' ', \file_get_contents($path)));

View

<img src="data:image/svg+xml;utf8,<?= $encodedSVG ?>">

⚠️ Do not convert to base64

It's less efficient in CPU time and also makes longer requests in size!

Know more about why

Upvotes: 4

CGriffin
CGriffin

Reputation: 1476

<svg> elements can be echoed directly onto a web page like any other element; there's no need to include it as an img src attribute. PHP's include can be used for this (ie. include('/path/to/image.svg')), amongst a myriad of other methods.

Alternatively, if for some reason you need to include the svg as an actual img tag, there's no need for file_get_contents or similar functions; an SVG can be linked as a source path like any other image type (ie. <image src="/path/to/image.svg">).

Upvotes: 7

Related Questions