If you're OK with using external scripts, you can use the SVG Sanitize package: https://packagist.org/packages/enshrined/svg-sanitize
While its primary purpose is sanitation, as a by-product of that process, it will also ensure your SVG is valid.
use enshrined\svgSanitize\Sanitizer;
// Create a new sanitizer instance
$sanitizer = new Sanitizer();
// Load the dirty svg (if it's an SVG file)
$dirtySVG = file_get_contents('filthy.svg');
// if it's a base64 encoded string, you can alternatively use the following
$base64_str = str_replace('data:image/svg+xml;base64,', '', $b64_string);
$base64_str = str_replace(' ', '+', $base64_str);
$dirtySVG = base64_decode($base64_str);
// Pass it to the sanitizer and get it back clean
if(!$cleanSVG = $sanitizer->sanitize($dirtySVG)){
//if this fails, the SVG was not valid.
}
// Now do what you want with your validated and clean SVG/XML data