DEV Community

Mathias Reker
Mathias Reker

Posted on

SVG files are everywhere — icons, logos, illustrations, UI graphics...

SVG files are everywhere - icons, logos, illustrations, UI graphics. They're lightweight, scalable, and web-friendly. But SVGs exported from design tools often contain:

  • Unnecessary metadata
  • Redundant attributes
  • Editor-specific footprints
  • Excess whitespace
  • Potentially unsafe elements

If you're working in PHP and want a robust, configurable, and security-aware SVG optimizer, there's now a purpose-built solution:

👉 https://github.com/MathiasReker/php-svg-optimizer

php-svg-optimizer is a lightweight PHP library designed to optimize, minify, and sanitize SVG files while staying compliant with SVG 2.0 specifications.

The result?

  • Smaller files
  • Cleaner markup
  • Standards-compliant SVG
  • Safer embedding
  • Visually identical output

Why SVG Optimization Matters

  1. Performance
    Smaller SVG files mean:
    Faster page loads
    Better Lighthouse scores
    Reduced bandwidth usage

  2. Security
    SVG is XML-based - and XML can contain:
    <script> tags
    Event handlers (onclick, etc.)
    External references
    Embedded malicious payloads

If you accept SVG uploads from users, sanitization isn't optional - it's critical.


Installation

composer require mathiasreker/php-svg-optimizer
Enter fullscreen mode Exit fullscreen mode

Two Ways to Use It:

1️⃣ Command Line (CLI)
Perfect for:
CI pipelines
Build steps
Batch processing
Pre-commit hooks

vendor/bin/svg-optimizer --with-all-rules process /path/to/svgs
Enter fullscreen mode Exit fullscreen mode

2️⃣ As a PHP Package
This is where the library really shines - fully configurable, fluent, and exception-safe.
Basic Example (Default Rules)

<?php

declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use MathiasReker\PhpSvgOptimizer\Service\Facade\SvgOptimizerFacade;

try {
    $svgOptimizer = SvgOptimizerFacade::fromFile('path/to/source.svg')
        ->withAllRules()
        ->optimize()
        ->saveToFile('path/to/output.svg');

    $metaData = $svgOptimizer->getMetaData();

    echo sprintf('Optimized size: %d bytes%s', $metaData->getOptimizedSize(), \PHP_EOL);
    echo sprintf('Original size: %d bytes%s', $metaData->getOriginalSize(), \PHP_EOL);
    echo sprintf('Size reduction: %d bytes%s', $metaData->getSavedBytes(), \PHP_EOL);
    echo sprintf('Reduction percentage: %s %%%s', $metaData->getSavedPercentage(), \PHP_EOL);
    echo sprintf('Processing time: %s seconds%s', $metaData->getOptimizationTime(), \PHP_EOL);
} catch (\Exception $exception) {
    echo $exception->getMessage();
}
Enter fullscreen mode Exit fullscreen mode

What Makes It Powerful?
The library implements the Strategy Pattern, where each optimization rule is encapsulated in its own class.
You can enable rules individually:

->withRules(
    convertColorsToHex: true,
    convertCssClassesToAttributes: true,
    convertEmptyTagsToSelfClosing: true,
    convertInlineStylesToAttributes: true,
    fixAttributeNames: false,
    flattenGroups: true,
    minifySvgCoordinates: true,
    minifyTransformations: true,
    removeAriaAndRole: true,
    removeComments: true,
    removeDataAttributes: false,
    removeDefaultAttributes: true,
    removeDeprecatedAttributes: true,
    removeDoctype: true,
    removeDuplicateElements: true,
    removeEmptyAttributes: true,
    removeEmptyGroups: true,
    removeEmptyTextElements: true,
    removeEnableBackgroundAttribute: false,
    removeInkscapeFootprints: true,
    removeInvisibleCharacters: true,
    removeMetadata: true,
    removeNonStandardAttributes: false,
    removeNonStandardTags: false,
    removeTitleAndDesc: true,
    removeUnnecessaryWhitespace: true,
    removeUnsafeElements: false,
    removeUnusedMasks: true,
    removeUnusedNamespaces: true,
    removeWidthHeightAttributes: false,
    sortAttributes: true,
)
Enter fullscreen mode Exit fullscreen mode

Secure SVG Upload Example

SvgOptimizerFacade::fromFile('uploaded.svg')
    ->withRules(sp
        removeUnsafeElements: true,
        removeNonStandardTags: true,
        removeNonStandardAttributes: true
    )
    ->allowRisky()
    ->optimize()
    ->saveToFile('sanitized.svg');
Enter fullscreen mode Exit fullscreen mode

This significantly reduces the risk of XSS when embedding user-uploaded SVGs.


Developer Experience

  • The project emphasizes:
  • PHPStan Level 9
  • 100% type coverage
  • High test coverage
  • Strategy-based architecture
  • Deterministic output

If you're working with SVGs in PHP, this tool deserves a place in your workflow.


⭐ If you find it useful, consider giving it a star on GitHub.

Top comments (0)