1 image.inc image_add_svg_attributes($svg_content, array $attributes)

Add attributes to an SVG string.

@since 1.28.0 Function added.

Parameters

string $svg_content: The entire contents of an SVG image.

array $attributes: An array of attributes to add to the SVG image. The special case of an "alt" attribute is automatically converted to a child <title> element, which is the accessible mechanism for alternative text within SVGs.

Return value

string: The SVG image contents with the attributes added.

Related topics

File

core/includes/image.inc, line 584
API for manipulating images.

Code

function image_add_svg_attributes($svg_content, array $attributes) {
  $doc = new DOMDocument();
  $doc->loadXML($svg_content);

  // Convert the alt attribute to a <title> element.
  if (isset($attributes['alt'])) {
    try {
      if (strlen($attributes['alt'])) {
        $title = $doc->createElement('title');
        $title->textContent = $attributes['alt'];
        $doc->firstChild->prepend($title);
      }
      // Remove any given <title> element if alt is an empty string.
      elseif ($doc->firstChild->firstChild && $doc->firstChild->firstChild->nodeName === 'title') {
        $doc->firstChild->removeChild($doc->firstChild->firstChild);
      }
    }
    catch (DOMException $e) {
    }
    unset($attributes['alt']);
  }

  foreach ($attributes as $attribute_name => $attribute_value) {
    $attribute_value = implode(' ', (array) $attribute_value);
    if (strlen($attribute_value)) {
      $doc->firstChild->setAttribute($attribute_name, $attribute_value);
    }
    else {
      $doc->firstChild->removeAttribute($attribute_name);
    }
  }
  return $doc->saveXML($doc->firstChild);
}