views:

77

answers:

2

Hello,

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>

Please help me, how to change this attribute value.

Regards, rafiq7s

A: 

One way could be to load the file as a string and then do the search and replace on it. You then can use loadXML http://www.php.net/manual/en/domdocument.loadxml.php and supply the changed string as a parameter.

zaf
-1 for suggesting search/replace when he's already using the DOM.
Adam Backstrom
Holy cow, so you cannot suggest better alternatives? Loosen up dude.
zaf
I already left [my own answer](http://stackoverflow.com/questions/2857113/how-to-change-the-attribute-value-of-svg-file/2857206#2857206). Just giving you feedback on the downvote. Every time someone suggests search/replace of XML/HTML data, God kills a kitten.
Adam Backstrom
Dude, I wasn't talking about you. Also people are not that stupid to need a link to your answer or want to hear the now boring chant that does not add anything to the conversation.
zaf
+2  A: 

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();
Adam Backstrom
+1 For me learning something new today.
zaf