How to change the attribute value of svg file
Asked Answered
A

1

5

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?

Apposition answered 18/5, 2010 at 12:17 Comment(0)
A
13

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();
Airport answered 18/5, 2010 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.