Skip to content

Instantly share code, notes, and snippets.

@ideogram
Created January 26, 2017 10:41
Show Gist options
  • Save ideogram/e9b7c6ad4d11c767cb7cd041f44073e0 to your computer and use it in GitHub Desktop.
Save ideogram/e9b7c6ad4d11c767cb7cd041f44073e0 to your computer and use it in GitHub Desktop.
CLI PHP script to merge a (large) number of SVG files into 1 svg sprite
<?php
/**
* Created by PhpStorm.
* User: maartenvandervelde
* Date: 16/01/17
* Time: 08:23
*/
/*
* First, optionally, use SVGO to compress all SVG's:
*
*
* BASH: *
* for f in ../sprite/*.svg; do svgo --input="$f" --enable=removeStyleElement --enable=transformsWithOnePath --enable=mergePath --pretty; done
*
*/
// File content
$sprite = [];
// Get source
$dir = "";
if (isset($argv) && isset($argv[1])){
$dir = $argv[1];
}
// Get destination
$dest = "svgmap.svg";
if (isset($argv) && isset($argv[2])){
$dest= $argv[2];
}
// Start filling the file array
$sprite[] = '<svg xmlns="http://www.w3.org/2000/svg">';
foreach (glob("$dir*.svg") as $filename) {
// Read SVG as XML object
$xml = simplexml_load_file($filename);
// Get and calculate attributes
$viewBox = $xml->attributes()['viewBox'];
$id = basename($filename,".svg");
$id_seo = seoUrl($id);
// Write out symbol and content of the SVG-tag
$sprite[] = "<symbol id='$id_seo' viewBox='$viewBox'>";
$sprite[] = "<title>$id_seo</title>";
foreach($xml as $element){
$sprite[] = $element->asXML();
}
$sprite[] = "</symbol>";
}
// Close SVG tag
$sprite[] = '</svg>';
// Write the array to a file
file_put_contents($dest, implode($sprite));
// From: http://stackoverflow.com/a/11330527/3010027
function seoUrl($string) {
//Lower case everything
$string = strtolower($string);
//Make alphanumeric (removes all other characters)
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
//Clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment