Skip to content

Instantly share code, notes, and snippets.

@KeenthemesHub
Created December 1, 2020 06:08
Show Gist options
  • Save KeenthemesHub/c6cd72020ae4280183827b3953ade40f to your computer and use it in GitHub Desktop.
Save KeenthemesHub/c6cd72020ae4280183827b3953ade40f to your computer and use it in GitHub Desktop.
public static function getSvgIcon($path, $class = '', $svgClass = '') {
$full_path = $path;
if ( ! file_exists($path)) {
return '<!-- SVG file not found; '.$path.' -->';
}
$svg_content = file_get_contents($path);
$dom = new DOMDocument();
$dom->loadXML($svg_content);
// remove unwanted comments
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//comment()') as $comment) {
$comment->parentNode->removeChild($comment);
}
// add class to svg
if ( ! empty($svgClass)) {
foreach ($dom->getElementsByTagName('svg') as $element) {
$element->setAttribute('class', $svgClass);
}
}
// remove unwanted tags
$title = $dom->getElementsByTagName('title');
if ($title['length']) {
$dom->documentElement->removeChild($title[0]);
}
$desc = $dom->getElementsByTagName('desc');
if ($desc['length']) {
$dom->documentElement->removeChild($desc[0]);
}
$defs = $dom->getElementsByTagName('defs');
if ($defs['length']) {
$dom->documentElement->removeChild($defs[0]);
}
// remove unwanted id attribute in g tag
$g = $dom->getElementsByTagName('g');
foreach ($g as $el) {
$el->removeAttribute('id');
}
$mask = $dom->getElementsByTagName('mask');
foreach ($mask as $el) {
$el->removeAttribute('id');
}
$rect = $dom->getElementsByTagName('rect');
foreach ($rect as $el) {
$el->removeAttribute('id');
}
$path = $dom->getElementsByTagName('path');
foreach ($path as $el) {
$el->removeAttribute('id');
}
$circle = $dom->getElementsByTagName('circle');
foreach ($circle as $el) {
$el->removeAttribute('id');
}
$use = $dom->getElementsByTagName('use');
foreach ($use as $el) {
$el->removeAttribute('id');
}
$polygon = $dom->getElementsByTagName('polygon');
foreach ($polygon as $el) {
$el->removeAttribute('id');
}
$ellipse = $dom->getElementsByTagName('ellipse');
foreach ($ellipse as $el) {
$el->removeAttribute('id');
}
$string = $dom->saveXML($dom->documentElement);
// remove empty lines
$string = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);
$cls = array('svg-icon');
if ( ! empty($class)) {
$cls = array_merge($cls, explode(' ', $class));
}
return '<span class="' . implode(' ', $cls) . '"><!--begin::Svg Icon | path:' . $full_path . '-->' . $string . '<!--end::Svg Icon--></span>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment