Rendering SVG Code to the DOM
Using PHP
Get an SVG file's contents and render it directly into the DOM of a web page.
This allows css to access the SVG and its paths and shapes (ex: to set size & fill).
Sample PHP Code
<a href='link' class='iconAsLink'>
<?php $fileName = "iconFileName"; ?>
<?php $className = "myClass"; ?>
<?= preg_replace("/{{class-name}}/", $className, file_get_contents("images/" . $fileName . ".svg")) ?>
</a>
Output Rendered to the DOM
<a href='link' class='iconAsLink'>
<svg id="icon" class="myClass" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500">
<path id="path1" d="M…Z" />
<path id="path2" d="M…Z" />
</svg>
</a>
Sample SCSS Styles
.iconAsLink {
svg {
.myClass {
width: auto;
height: 24px;
fill: orange;
#path2 {
fill: chocolate;
opacity: .5;
}
}
}
}
The scss doesn't necessarily need this much specificity.
- The <svg> can be referenced directly by its id or class
- Paths and shapes can be referenced directly by their id