How to Get PHP to Play Nicely with SVG Files
Update (1/13/16): This article has been updated to stay in line with current best practices for working with SVG files.
I came across an error I hadn’t seen before last week when using PHP to include SVG files into my PHP file. I used this approach to include the SVG inline:
<?php include("icons/my-icon.svg"); ?>
Everything worked fine in my development environment with Apache, but when I deployed my code to my staging environment, which in this case was on Bluehost, I saw this:
PHP Parse error: syntax error, unexpected version (T_STRING)
After some investigation, it turns out that PHP was unable to parse the beginning of the SVG file at the point where the XML version was defined:
<?xml version="1.0" encoding="utf-8"?>
Luckily, CSS Tricks has documented an easy fix for this. I just had to use PHP's filegetcontents() function instead, which resulted in:
<?php echo file_get_contents("icons/my-icon.svg"); ?>
One alternative fix is to just remove this xml header tag from your SVG file completely, as this is not needed by the browser. SVG optimization tools like the web-based SVGOMG tool do this automatically for you.
One note: in order to see PHP errors like this in the first place, you need to have
display_errors = On set in your php.ini configuration file. Otherwise you’ll just see a half-rendered page, with PHP giving up at the point that the error occurred.
Hope this helps someone out there who experiences the same problem!