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

霸气de小男生 提交于 2021-02-09 08:50:09

问题


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.


回答1:


<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">).




回答2:


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



来源:https://stackoverflow.com/questions/41171623/use-php-to-prep-svg-file-for-use-in-img-tag-data-uri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!