Adding Font Awesome SVG icons with PHP

Copy Link

Font Awesome is a popular icon library. It used to be an icon font, but now in Font Awesome 5 it also come with SVG icons.

One reason of Font Awesome’s popularity is the ease of use. You add a CSS file and a JS file to your document, and you’re set. You can then add the icons like so:

<i class="fas fa-home"></i>

When the SVG icons option was introduced, they kept it just as simple which is great because SVGs are great.

However, you may not necessairly want to load extra Javascript on your PHP application or website just to include icons. And it would be nice to have the SVG icons on there as soon as the page loads - which is one of the benefits of using inline SVGs to begin with.

So I wrote a PHP class to allow me to add the SVG icons almost just as easily. You can find it on GItHub.

$FA = new FontAwesomeSVG($dir);

echo $FA->get_svg('fas fa-file');

I’ve kept the same behaviour when it comes to classes and attributes. And you also still get the auto-accessibility feature.

For semantic icons, the class adds a <title> inside the SVG like the default JS method does. However it does not add the aria-labelledby attribute at the moment.

Example usage

I have also built a Perch app to make it possible to add the SVG icons via PHP or directly in a Perch template. Using the app I can add icons to Perch templates simply like so:

<perch:fa id="home" icon="fas fa-home" html >

Or via PHP like so:

pipit_fa_icon('fas fa-home');
Get in Touch