Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the attribute value of svg file

In samplexml.svg there is a node

<image width="744" height="1052" xlink:href="image1.png"/>

I need to replace "image1.png" with another value like "image2.png". Please guide me with sample code how to to that.

I could get the attribute value "image1.png". Here is the code:

$xdoc = new DomDocument;
$xdoc->Load('samplexml.svg');
$tagName = $xdoc->getElementsByTagName('image')->item(0);
$attribNode = $tagName->getAttributeNode('xlink:href');

echo "Attribute Name  : " . $attribNode->name . "<br/>";
echo "Attribute Value : " . $attribNode->value;

Here is samplexml.svg:

<svg>
    <g>
        <title>Test title</title>
        <image x="0" y="0" width="744" height="1052" xlink:href="image1.png"/>
    </g>
</svg>

How do I programmatically change the xlink:href value?

like image 797
user577443 Avatar asked May 18 '10 12:05

user577443


People also ask

How do I change SVG attributes?

Changing Attribute Values Once you have obtained a reference to the SVG element you can change its attributes using the setAttribute() function. Here is an example: var svgElement = document. getElementById("rect1"); svgElement.

What are the attributes of SVG?

SVG attributes by categoryrequiredExtensions , requiredFeatures , systemLanguage .

Can SVG have an ID?

The id attribute assigns a unique name to an element. You can use this attribute with any SVG element.

What is transform in SVG?

The transform attribute defines a list of transform definitions that are applied to an element and the element's children. Note: As of SVG2, transform is a presentation attribute, meaning it can be used as a CSS property.


1 Answers

Use DOMElement::setAttributeNS():

$xdoc = new DomDocument;
$xdoc->Load('svg.xml');
$tagName = $xdoc->getElementsByTagName('image')->item(0);
$attribNode = $tagName->getAttributeNode('xlink:href');

echo "Attribute Name  : " . $attribNode->name . "<br/>";
echo "Attribute Value : " . $attribNode->value;

$tagName->setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'image2.png');

echo $xdoc->saveXML();
like image 87
Annika Backstrom Avatar answered Sep 17 '22 11:09

Annika Backstrom