It’s sometimes convenient to generate the SVG dynamically with PHP. Specific scenarios where it might be appropriate to use SVG dynamically generated with PHP are:

  • To recolor icons and design elements based on the context
  • To make design elements customizable by the user
  • As an alternative to libraries that generates png, gif, or jpg 
  • For data visualization

In this article, I’m going to cover different techniques to create SVG images with PHP.

Generate an SVG image from an existing file

With the file_get_content() function, you can transfer the SVG content from a file to a string. The resulting string can be then be modified based on your needs, for example, by adding classes or inline styles.

When working with SVG imported with file_get_content(), a necessary precaution is to sanitize the SVG content before echoing it in the HTML. In the example below, I used a PHP package named svg-sanitize to perform this operation.

<?php

//Store the svg icon URL in a variable
$svg_icon_url = 'http://localhost/ws/svg-icon.svg';

//Use file_get_contents() to retrieve the content of the svg
$svg_icon_content = file_get_contents( $svg_icon_url );

//Modify the SVG content based on your needs

//Sanitize the SVG content. In this example I will use https://packagist.org/packages/enshrined/svg-sanitize package
require 'vendor/autoload.php';
use enshrined\svgSanitize\Sanitizer;
$sanitizer = new Sanitizer();
$svg_icon_content = $sanitizer->sanitize($svg_icon_content);

//Print the SVG HTML
echo $svg_icon_content;

One advantage of this technique is that no additional HTTP requests are required to load the SVG files because the SVG code is injected directly into the HTML of the document.

It’s worth noting that using too many file_get_contents() calls might increase the time required by PHP to generate the page. Fortunately, a caching plugin or a custom caching solution can quickly solve this performance problem.

Echo the SVG with PHP

Another common technique to create a dynamic SVG with PHP is to echo the SVG content with PHP instructions.

To use this technique, first, change the extension of the SVG file from “.svg” to “.php”. This adjustment instructs the server to process the file as a PHP file.

Second, add the Content-type: image/svg+xml HTTP header to the generated document. This second change tells the browser to display the document as an SVG.

In the following example, the same image will be first created as a static SVG file and then as a PHP file.

The original static SVG file:

<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100">
<rect x="0" y="0" width="40" height="40" style="fill: #0000FF"/>
</svg>

The PHP version of the SVG:

<?php

// Add the proper header
header('Content-Type: image/svg+xml');

// Echo the SVG content
echo '<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100">
<rect x="0" y="0" width="40" height="40" style="fill: #0000FF"/>
</svg>';

An exciting possibility associated with the use of PHP files is that you can process the GET parameters and modify the SVG based on these values.

In this example, the color parameter is used to modify the color of the image dynamically:

<img src="https://example.com/image.php?color=ff0000">

When you use GET parameters, don’t forget to sanitize the values appropriately. Note that the type of sanitization depends on the data. In the example below, I used a function that sanitizes hexadecimal colors taken from the WordPress core.

<?php

// Add the proper header
header('Content-Type: image/svg+xml');

//Sanitization the hex color.
$color = sanitize_hex_color( '#' . $_GET['color'] );

// Echo the SVG content
echo '<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100">
<rect x="0" y="0" width="40" height="40" style="fill: ' . htmlspecialchars( $color, ENT_QUOTES ) . '"/>
</svg>';

/**
 * Sanitize HEX color.
 *
 * A hex sanitization function copied from the WordPress core.
 *
 * @param string $color setting input.
 *
 * @return string setting input value.
 */
function sanitize_hex_color( $color ) {

    if ( '' === $color ) {
        return '';
    }

    // 3 or 6 hex digits, or the empty string.
    if ( preg_match( '|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) ) {
        return $color;
    }

    return '';

}

With a dedicated PHP library

The php-svg PHP library can generate SVG from instructions provided with PHP.

This MIT licensed library is available on GitHub. You can easily integrate it in your project with composer, specifically by using the meyfa/php-svg package.

Although not very well documented, this library is easy to use and with a small codebase. Consequently, you can quickly learn to draw lines, paths, and shapes simply by looking at the library source code.

Below you can find the example provided in the library documentation on GitHub, which illustrates how to draw a simple blue rectangle:

<?php

require 'vendor/autoload.php';

use SVG\SVG;
use SVG\Nodes\Shapes\SVGRect;

// Setup the document
$image = new SVG(100, 100);
$doc = $image->getDocument();

// Create a small blue rectangle
$square = new SVGRect(0, 0, 40, 40);
$square->setStyle('fill', '#0000FF');
$doc->addChild($square);

// Add the proper header and echo the SVG
header('Content-Type: image/svg+xml');
echo $image;

In this second example, I will use the SVGLine class to draw a small red horizontal line.

<?php

require 'vendor/autoload.php';

use SVG\SVG;
use SVG\Nodes\Shapes\SVGLine;

// Setup the document
$image = new SVG(100, 100);
$doc = $image->getDocument();

// Create a small red horizontal line
$line = new SVGLine(20, 20, 60, 20);
$line->setStyle('stroke', '#ff0000');
$doc->addChild($line);

// Add the proper header and echo the SVG
header('Content-Type: image/svg+xml');
echo $image;

Dynamically modify an SVG without PHP

Note that you can also modify the style of an SVG without PHP only by using CSS rules.

To achieve this, assign custom classes to the SVG elements and then modify these elements with CSS rules.

In the example below, I added the customizable-rectangle class to a rect element.

<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100">
<rect class="customizable-rectangle" x="0" y="0" width="40" height="40"/>
</svg>

This CSS rule assigns red as the fill color and blue as the stroke color.

.customizable-rectangle{
    fill: red;
    stroke: blue;
}

Pass parameters to a JavaScript file

If you plan to create or modify the SVG with JavaScript, you might consider adding data to the page. For example, in the data attribute of an HTML element or as JavaScript variables.

For more information on this process, check out this other article on dynamically generating SVG with JavaScript.