Reputation: 4568
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
Reputation: 2980
$encodedSVG = \rawurlencode(\str_replace(["\r", "\n"], ' ', \file_get_contents($path)));
<img src="data:image/svg+xml;utf8,<?= $encodedSVG ?>">
It's less efficient in CPU time and also makes longer requests in size!
Upvotes: 4
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