PHP Echo and Variable Inside SVG


facebooktwitterpinterestgoogleredditslashdottumblr

As I'm getting more and more in love with Scalable Vector Graphics I had to find a way to make my SVGs understand PHP. I searched the answer for couple of hours and the result was pretty simple actually.


So I made a plain SVG document in Inkscape and exported it. Then I opened the document inside text editor and started out by trying to insert PHP tags inside SVG document. As you might think it didn't end well. Why? Because the SVG image showed the input just as it was written: Just a plain php code.

The comment that saved me

Then I discovored a post in Stack Overflow about variables in SVG. The post didn't have a proper answer but what I found in the comment section was just what I needed. Guy named Robert was asking: "why not generate the whole thing in PHP?"

Renaming an SVG to PHP

I got pretty close to the solution by renaming the SVG document to PHP but there was still something wrong: I got the error message. Appears that after renaming the document to PHP I had to delete everything before SVG tags. Looks like the XML tag left from SVG made the PHP document go crazy. Delete: <?xml version="1.0" encoding="UTF-8" standalone="no"?>.

Just insert the code between tags

After getting rid of the XML part and starting the document with plain SVG tag everything was good. All I had to do now is to insert PHP tags inside the SVG whenever I wanted. I was experimenting with simple variables and <?php echo "Hello world!"; ?>.

Include the document as PHP

As you might have guessed you need to include the newly created SVG document as PHP. Simply use the standard <?php include 'yourrenamedsvg.php';?>.

Make sure to adjust viewBox, width, height

There is one more thing to do. Search for the viewBox, width and height inside the SVG document. As my SVG was saved to have width and height measured as mm I had to change that to what I wanted it to be. I changed it to 100% width and auto height. Inkscape does a pretty good job with the viewBox attribute so I didn't have to touch that.



Last update: 2018-04-30 (Y,M,D)

Read similar posts


2018-10-08 Creating a template for a vector based design applications
2018-09-26 Creating a multi-use footer template for all my websites
2018-09-13 I made a HTML and Javascript only replica of a popular WordPress template
2018-09-11 Best webpages for royalty-free stock photos
2018-04-30 Scalable Vector Graphics Chart with PHP Variables
2018-04-30 PHP Echo and Variable Inside SVG

Search messtwice.com: