Skip to content Skip to sidebar Skip to footer

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 =

Solution 1:

<svg> elements can be echoed directly onto a web page like any other element; there's no need to include it as an imgsrc 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">).

Solution 2:

Solution

Controller

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

View

<imgsrc="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

Post a Comment for "Use Php To Prep Svg File For Use In Img Tag Data Uri"