Monthly Archives: May 2010

How to change the attribute value of a node in svg (or xml) file by php

Recently I have faced a problem on changing the attribute value of an svg file. At last found a solution.

Lets say an svg file sample.svg:

<svg width="744" height="1052" xmlns="" xmlns:se="" xmlns:xlink="">
		<title>Test Title</title>
		<image x="0" y="0" width="744" height="1052" id="svg_1" xlink:href="image1.png" />

Now, I want to replace image1.png with image2.png. Here is the code:

$xdoc = new DomDocument;

$tagName = $xdoc->getElementsByTagName('image')->item(0);
$attribNode = $tagName->getAttributeNode('xlink:href');
$tagName->setAttributeNS('', 'xlink:href', 'image2.png');
$newFileContent = $xdoc->saveXML();

$fh = fopen('sample.svg', 'w') or die("can't open file");
fwrite($fh, $newFileContent);

setAttributeNS(), saveXML()