Strip XML Version & Encoding from an SVG File with PHP

Say you want to grab a file, so you can then have the SVG’s actual code display in your HTML…instead of just putting the file.svg in an img tag.

Well, here’s how we can go about that.


$svg_file = '/path/to/some/file.svg'; // for WordPress, see the next code block below
$svg_content = file_get_contents($svg_file);
$allowed = array('svg','g','path','a','animate','a','animate','animateMotion','animateTransform','circle','clipPath','defs','desc','ellipse','feBlend','feColorMatrix','feComponentTransfer','feComposite','feConvolveMatrix','feDiffuseLighting','feDisplacementMap','feDistantLight','feDropShadow','feFlood','feFuncA','feFuncB','feFuncG','feFuncR','feGaussianBlur','feImage','feMerge','feMergeNode','feMorphology','feOffset','fePointLight','feSpecularLighting','feSpotLight','feTile','feTurbulence','filter','foreignObject','image','line','linearGradient','marker','mask','metadata','mpath','path','pattern','polygon','polyline','radialGradient','rect','script','set','stop','style','svg','switch','symbol','text','textPath','title','tspan','use','view');
$svg_content = strip_tags($svg_content, $allowed);
$output = $svg_content;

That will strip out that nasty <!--?xml version="1.0" encoding="UTF-8"?--> stuff.

For WordPress

If you know the attachment ID from the Media Library.


$attachment_ID = 100; // where 100 is the $attachment_ID
$svg_file = get_attached_file($attachment_ID); // for WordPress
$svg_content = file_get_contents($svg_file);
$allowed = array('svg','g','path','a','animate','a','animate','animateMotion','animateTransform','circle','clipPath','defs','desc','ellipse','feBlend','feColorMatrix','feComponentTransfer','feComposite','feConvolveMatrix','feDiffuseLighting','feDisplacementMap','feDistantLight','feDropShadow','feFlood','feFuncA','feFuncB','feFuncG','feFuncR','feGaussianBlur','feImage','feMerge','feMergeNode','feMorphology','feOffset','fePointLight','feSpecularLighting','feSpotLight','feTile','feTurbulence','filter','foreignObject','image','line','linearGradient','marker','mask','metadata','mpath','path','pattern','polygon','polyline','radialGradient','rect','script','set','stop','style','svg','switch','symbol','text','textPath','title','tspan','use','view');
$svg_content = strip_tags($svg_content, $allowed);
$output = $svg_content;

Enjoy!

Up Next: Create an Advanced Custom Fields "Code" Field