{"id":19810235,"url":"https://github.com/mathiasreker/php-svg-optimizer","last_synced_at":"2026-02-18T21:10:37.298Z","repository":{"id":254695178,"uuid":"846285888","full_name":"MathiasReker/php-svg-optimizer","owner":"MathiasReker","description":"php-svg-optimizer  is a lightweight PHP library designed to optimize, minify, and sanitize SVG files","archived":false,"fork":false,"pushed_at":"2026-02-15T07:25:50.000Z","size":10284,"stargazers_count":30,"open_issues_count":0,"forks_count":6,"subscribers_count":1,"default_branch":"develop","last_synced_at":"2026-02-15T13:39:52.391Z","etag":null,"topics":["clean","compress","minifier","optimizer","performance","php","php-library","sanitizer","svg"],"latest_commit_sha":null,"homepage":"https://github.com/MathiasReker/php-svg-optimizer","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MathiasReker.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":["MathiasReker"]}},"created_at":"2024-08-22T22:30:12.000Z","updated_at":"2026-02-15T07:25:53.000Z","dependencies_parsed_at":"2026-01-14T21:06:03.677Z","dependency_job_id":"42765f51-c830-4008-87c7-324e880b6272","html_url":"https://github.com/MathiasReker/php-svg-optimizer","commit_stats":null,"previous_names":["mathiasreker/php-svg-optimizer"],"tags_count":76,"template":false,"template_full_name":null,"purl":"pkg:github/MathiasReker/php-svg-optimizer","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MathiasReker%2Fphp-svg-optimizer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MathiasReker%2Fphp-svg-optimizer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MathiasReker%2Fphp-svg-optimizer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MathiasReker%2Fphp-svg-optimizer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MathiasReker","download_url":"https://codeload.github.com/MathiasReker/php-svg-optimizer/tar.gz/refs/heads/develop","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MathiasReker%2Fphp-svg-optimizer/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29596186,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-18T20:59:56.587Z","status":"ssl_error","status_checked_at":"2026-02-18T20:58:41.434Z","response_time":162,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["clean","compress","minifier","optimizer","performance","php","php-library","sanitizer","svg"],"created_at":"2024-11-12T09:20:04.889Z","updated_at":"2026-02-18T21:10:37.212Z","avatar_url":"https://github.com/MathiasReker.png","language":"PHP","funding_links":["https://github.com/sponsors/MathiasReker"],"categories":[],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003ePHP SVG Optimizer\u003c/h1\u003e\n\n[![Packagist Version](https://img.shields.io/packagist/v/MathiasReker/php-svg-optimizer.svg)](https://packagist.org/packages/MathiasReker/php-svg-optimizer)\n[![Packagist Downloads](https://img.shields.io/packagist/dt/MathiasReker/php-svg-optimizer.svg?color=%23ff007f)](https://packagist.org/packages/MathiasReker/php-svg-optimizer)\n[![CI status](https://github.com/MathiasReker/php-svg-optimizer/actions/workflows/ci.yml/badge.svg?branch=develop)](https://github.com/MathiasReker/php-svg-optimizer/actions/workflows/ci.yml)\n[![Contributors](https://img.shields.io/github/contributors/MathiasReker/php-svg-optimizer.svg)](https://github.com/MathiasReker/php-svg-optimizer/graphs/contributors)\n[![Forks](https://img.shields.io/github/forks/MathiasReker/php-svg-optimizer.svg)](https://github.com/MathiasReker/php-svg-optimizer/network/members)\n[![Stargazers](https://img.shields.io/github/stars/MathiasReker/php-svg-optimizer.svg)](https://github.com/MathiasReker/php-svg-optimizer/stargazers)\n[![Issues](https://img.shields.io/github/issues/MathiasReker/php-svg-optimizer.svg)](https://github.com/MathiasReker/php-svg-optimizer/issues)\n[![MIT License](https://img.shields.io/github/license/MathiasReker/php-svg-optimizer.svg)](https://github.com/MathiasReker/php-svg-optimizer/blob/develop/LICENSE.txt)\n\n`php-svg-optimizer` is a PHP library designed to optimize SVG files by applying various transformations and cleanup\noperations. The library ensures that the optimized SVG files are **compliant with SVG 2.0** specifications.\n\nThe tool strives to optimize as much as possible without losing any data that could distort the image's quality,\nensuring the resulting SVG remains visually identical to the original while being more efficient in terms of size and\nperformance.\n\n### Versions \u0026 Dependencies\n\n| Version | PHP  | Documentation                                                |\n|---------|------|--------------------------------------------------------------|\n| ^5.2    | ^8.3 | [current](https://github.com/MathiasReker/php-svg-optimizer) |\n\n### Requirements\n\n- `ext-dom`: Required PHP extension for XML handling.\n- `ext-libxml`: Required PHP extension for XML error handling.\n\n### Installation\n\nTo install the library, run:\n\n```bash\ncomposer require mathiasreker/php-svg-optimizer\n```\n\n### Using the Library\n\nYou can use this library either as a **command-line tool (CLI)** or as a **standalone package**.\n\n---\n\n## CLI tool\n\n#### Usage\n\n![Demo GIF](assets/demo.gif)\n\n```bash\nvendor/bin/svg-optimizer [options] process \u003cpath1\u003e \u003cpath2\u003e ...\n```\n\n```bash\nOptions:\n-h , --help               Display help for the command.\n-c , --config             Path to a JSON file with custom optimization rules. If not provided, all default optimizations will be applied.\n-d , --dry-run            Only calculate potential savings without modifying the files.\n-q , --quiet              Suppress all output except errors.\n-v , --version            Display the version of the library.\n\nCommands:\nProcess                   Provide a list of directories or files to process.\n```\n\n#### Examples:\n\n```bash\nvendor/bin/svg-optimizer --dry-run process /path/to/svgs\nvendor/bin/svg-optimizer --config=config.json process /path/to/file.svg\nvendor/bin/svg-optimizer --quiet process /path/to/file.svg\n```\n\n#### Config file example:\n\n```json\n{\n  \"convertColorsToHex\": true,\n  \"flattenGroups\": true,\n  \"minifySvgCoordinates\": true,\n  \"minifyTransformations\": true,\n  \"removeComments\": true,\n  \"removeDefaultAttributes\": true,\n  \"removeDeprecatedAttributes\": true,\n  \"removeDoctype\": true,\n  \"removeEnableBackgroundAttribute\": true,\n  \"removeEmptyAttributes\": true,\n  \"removeMetadata\": true,\n  \"removeInvisibleCharacters\": true,\n  \"removeTitleAndDesc\": true,\n  \"sortAttributes\": true,\n  \"convertEmptyTagsToSelfClosing\": true,\n  \"removeUnnecessaryWhitespace\": true\n}\n```\n\n## Package\n\n\u003e To ensure robustness when using the library, it's crucial to handle exceptions, as invalid or malformed SVG files\n\u003e could lead to runtime errors. Catching these exceptions will allow you to manage potential issues gracefully and\n\u003e prevent\n\u003e your application from crashing.\n\n### Example specifying rules\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse MathiasReker\\PhpSvgOptimizer\\Services\\SvgOptimizerService;\n\ntry {\n    $svgOptimizer = SvgOptimizerService::fromFile('path/to/source.svg')\n        -\u003ewithRules(\n            convertColorsToHex: true,\n            flattenGroups: true,\n            minifySvgCoordinates: true,\n            minifyTransformations: true,\n            removeComments: true,\n            removeDefaultAttributes: true,\n            removeDeprecatedAttributes: true,\n            removeDoctype: true,\n            removeEnableBackgroundAttribute: true,\n            removeEmptyAttributes: true,\n            removeMetadata: true,\n            removeTitleAndDesc: false,\n            sortAttributes: true,\n            convertEmptyTagsToSelfClosing: true,\n            removeUnnecessaryWhitespace: true,\n         )\n        -\u003eoptimize()\n        -\u003esaveToFile('path/to/output.svg');\n} catch (\\Exception $exception) {\n    echo $exception-\u003egetMessage();\n}\n```\n\n### Example parsing from a file and saving to a file using default rules\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse MathiasReker\\PhpSvgOptimizer\\Services\\SvgOptimizerService;\n\ntry {\n    $svgOptimizer = SvgOptimizerService::fromFile('path/to/source.svg')\n        -\u003eoptimize()\n        -\u003esaveToFile('path/to/output.svg');\n\n    $metaData = $svgOptimizer-\u003egetMetaData();\n\n    echo sprintf('Optimized size: %d bytes%s', $metaData-\u003egetOptimizedSize(), \\PHP_EOL);\n    echo sprintf('Original size: %d bytes%s', $metaData-\u003egetOriginalSize(), \\PHP_EOL);\n    echo sprintf('Size reduction: %d bytes%s', $metaData-\u003egetSavedBytes(), \\PHP_EOL);\n    echo sprintf('Reduction percentage: %s %%%s', $metaData-\u003egetSavedPercentage(), \\PHP_EOL);\n} catch (\\Exception $exception) {\n    echo $exception-\u003egetMessage();\n}\n\n```\n\n### Example parsing from a file and returning the content using default rules\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse MathiasReker\\PhpSvgOptimizer\\Services\\SvgOptimizerService;\n\ntry {\n    $svgOptimizer = SvgOptimizerService::fromFile('path/to/source.svg')\n        -\u003eoptimize();\n\n    echo sprintf('Get content: ', $svgOptimizer-\u003egetContent(), \\PHP_EOL);\n     \n    $metaData = $svgOptimizer-\u003egetMetaData();\n\n    echo sprintf('Optimized size: %d bytes%s', $metaData-\u003egetOptimizedSize(), \\PHP_EOL);\n    echo sprintf('Original size: %d bytes%s', $metaData-\u003egetOriginalSize(), \\PHP_EOL);\n    echo sprintf('Size reduction: %d bytes%s', $metaData-\u003egetSavedBytes(), \\PHP_EOL);\n    echo sprintf('Reduction percentage: %s %%%s', $metaData-\u003egetSavedPercentage(), \\PHP_EOL);\n} catch (\\Exception $exception) {\n    echo $exception-\u003egetMessage();\n}\n```\n\n### Example parsing from a string and returning the content using default rules\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nrequire_once __DIR__ . '/vendor/autoload.php';\n\nuse MathiasReker\\PhpSvgOptimizer\\Services\\SvgOptimizerService;\n\ntry {\n    $svgOptimizer = SvgOptimizerService::fromString('\u003csvg\u003e...\u003c/svg\u003e')\n        -\u003eoptimize();\n\n    echo sprintf('Content: ', $svgOptimizer-\u003egetContent(), \\PHP_EOL);\n\n    $metaData = $svgOptimizer-\u003egetMetaData();\n\n    echo sprintf('Optimized size: %d bytes%s', $metaData-\u003egetOptimizedSize(), \\PHP_EOL);\n    echo sprintf('Original size: %d bytes%s', $metaData-\u003egetOriginalSize(), \\PHP_EOL);\n    echo sprintf('Size reduction: %d bytes%s', $metaData-\u003egetSavedBytes(), \\PHP_EOL);\n    echo sprintf('Reduction percentage: %s %%%s', $metaData-\u003egetSavedPercentage(), \\PHP_EOL);\n} catch (\\Exception $exception) {\n    echo $exception-\u003egetMessage();\n}\n```\n\n### Documentation\n\nStatic factory method to create `SvgOptimizerService` from a file path.\n\n```php\n$svgOptimizer = SvgOptimizerService::fromFile('path/to/source.svg');\n```\n\nStatic factory method to create `SvgOptimizerService` from a string.\n\n```php\n$svgOptimizer = SvgOptimizerService::fromString('\u003csvg\u003e...\u003c/svg\u003e');\n```\n\n#### `withRules` Method\n\nConfigure which SVG optimization rules to apply. The method accepts boolean parameters that determine whether specific\nrules should be enabled or disabled.\n\n##### Parameters:\n\nRemoves `\u003ctitle\u003e` and `\u003cdesc\u003e` tags from the SVG:\n\n```php\n$svgOptimizer-\u003ewithRules(removeTitleAndDesc: true);\n```\n\nRemoves all comments from the SVG:\n\n```php\n$svgOptimizer-\u003ewithRules(removeComments: true);\n```\n\nSorts attributes within each element:\n\n```php\n$svgOptimizer-\u003ewithRules(sortAttributes: true);\n```\n\nRemoves default attribute values that match common defaults:\n\n```php\n$svgOptimizer-\u003ewithRules(removeDefaultAttributes: true);\n```\n\nRemoves deprecated attributes from the SVG:\n\n```php\n$svgOptimizer-\u003ewithRules(removeDeprecatedAttributes: true);\n```\n\nRemoves `\u003cmetadata\u003e` tags from the SVG:\n\n```php\n$svgOptimizer-\u003ewithRules(removeMetadata: true);\n```\n\nRemoves invisible characters from the SVG:\n\n```php\n$svgOptimizer-\u003ewithRules(removeInvisibleCharacters: true);\n```\n\nFlattens nested `\u003cg\u003e` elements, moving their child elements up to the parent node:\n\n```php\n$svgOptimizer-\u003ewithRules(flattenGroups: true);\n```\n\nConverts `rgb()` color values to hexadecimal format:\n\n```php\n$svgOptimizer-\u003ewithRules(convertColorsToHex: true);\n```\n\nMinifies coordinate values by removing unnecessary precision:\n\n```php\n$svgOptimizer-\u003ewithRules(minifySvgCoordinates: true);\n```\n\nMinifies transformation attributes by removing redundant values:\n\n```php\n$svgOptimizer-\u003ewithRules(minifyTransformations: true);\n```\n\nRemoves the SVG doctype declaration:\n\n```php\n$svgOptimizer-\u003ewithRules(removeDoctype: true);\n```\n\nRemoves the `enable-background` attribute from the SVG:\n\n```php\n$svgOptimizer-\u003ewithRules(removeEnableBackgroundAttribute: true);\n```\n\nRemoves empty attributes from the SVG:\n\n```php\n$svgOptimizer-\u003ewithRules(removeEmptyAttributes: true);\n```\n\nConverts empty tags to self-closing tags:\n\n```php\n$svgOptimizer-\u003ewithRules(convertEmptyTagsToSelfClosing: true);\n```\n\nCleans up unnecessary whitespace in the SVG:\n\n```php\n$svgOptimizer-\u003ewithRules(removeUnnecessaryWhitespace: true);\n```\n\nAll options are set to true by default. You can configure them individually by passing the desired values to it:\n\n```php\n$svgOptimizer-\u003ewithRules(\n   convertColorsToHex: true,\n   flattenGroups: true,\n   minifySvgCoordinates: true,\n   minifyTransformations: true,\n   removeComments: true,\n   removeDefaultAttributes: true,\n   removeDeprecatedAttributes: true,\n   removeDoctype: true,\n   removeEmptyAttributes: true,\n   removeMetadata: true,\n   removeInvisibleCharacters: true,\n   removeTitleAndDesc: true,\n   sortAttributes: true,\n   convertEmptyTagsToSelfClosing: true,\n   removeUnnecessaryWhitespace: true,\n);\n```\n\n#### `optimize` Method\n\nFinalizes the optimization process and generates the optimized SVG file.\n\n```php\n$svgOptimizer-\u003eoptimize();\n```\n\n#### `saveToFile` Method\n\nSaves the optimized SVG file to the specified path.\n\n```php\n$svgOptimizer-\u003esaveToFile('path/to/output.svg');\n```\n\n#### `getContent` Method\n\nReturns the optimized SVG content.\n\n```php\n$svgOptimizer-\u003egetContent();\n```\n\n#### `getOptimizedSize` Method\n\nReturns the size of the optimized SVG file.\n\n```php\n$svgOptimizer-\u003egetMetaData()-\u003egetOptimizedSize();\n```\n\n#### `getOriginalSize` Method\n\nReturns the size of the original SVG file.\n\n```php\n$svgOptimizer-\u003egetMetaData()-\u003egetOriginalSize();\n```\n\n#### `getSavedBytes` Method\n\nReturns the number of bytes saved by the optimization process.\n\n```php\n$svgOptimizer-\u003egetMetaData()-\u003egetSavedBytes();\n```\n\n#### `getSavedPercentage` Method\n\nReturns the percentage of bytes saved by the optimization process.\n\n```php\n$svgOptimizer-\u003egetMetaData()-\u003egetSavedPercentage();\n```\n\n### Roadmap\n\nFor a complete list of proposed features and known issues, see\nthe [open issues](https://github.com/MathiasReker/php-svg-optimizer/issues).\n\n### Contributing\n\nWe welcome all contributions! If you have ideas for improvements, feel free to fork the repository and submit a pull\nrequest. You can also open an issue. If you find this project helpful, don’t forget to give it a star!\n\n#### Library Structure and Contribution Guide\n\nThe library implements the Strategy Pattern, where strategies are encapsulated as \"rules\" located in the\n`/src/Services/Rules` directory.\n\n##### Adding a New Rule\n\n### 1. **Create the Rule**\n\nCreate a new **final class** in the `/src/Services/Rules` directory and implement the `SvgOptimizerRuleInterface`. This\ninterface will define the logic for your rule.\n\n### 2. **Write Tests**\n\nWrite comprehensive **unit tests** for your rule in the `/tests/Unit/Services/Rules` directory. Ensure the tests cover\nvarious scenarios to verify the correct behavior and edge cases for your rule.\n\n### 3. **Integrate the Rule**\n\n- **Register the rule** in the SVG optimizer builder located at `/src/Services/SvgOptimizerService.php`.\n- **Add your rule to the rule enum** in `/src/Enums/Rule.php`.\n- **Include the rule in the CLI tool** by updating `/src/Commands/SvgOptimizerCommand.php`.\n\n### 4. **Update Documentation**\n\nDocument the functionality and purpose of your rule in the `README.md` to ensure users understand its behavior and\nusage.\n\n#### Docker\n\nTo use the project with Docker, you can start the container using:\n\n```bash\ndocker-compose up -d\n```\n\nThen, access the container:\n\n```bash\ndocker exec -it php-svg-optimizer bash\n```\n\n#### Tools\n\nRun PHPStan:\n\n```bash\ncomposer phpstan\n```\n\nRun tests:\n\n```bash\ncomposer test\n```\n\nFormat code:\n\n```bash\ncomposer format\n```\n\n### License\n\nThis project is licensed under the MIT License. See\nthe [LICENSE](https://github.com/MathiasReker/php-svg-optimizer/blob/develop/LICENSE) file for more information.\n\n### Disclaimer\n\nAlthough the tool has been thoroughly tested and is built in a way that avoids risky changes, its use is at your own\nrisk. We cannot guarantee that it will be fully compatible with all SVG files or workflows. It is highly recommended to\ntest the tool with sample SVG files and ensure compatibility with your specific use case before using it in a production\nenvironment.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmathiasreker%2Fphp-svg-optimizer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmathiasreker%2Fphp-svg-optimizer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmathiasreker%2Fphp-svg-optimizer/lists"}